Compare commits

..
Author SHA1 Message Date
asarium c084a432d4 Add lights to thrusters 2020-05-02 15:33:52 +02:00
1159 changed files with 33095 additions and 97579 deletions

No files matched your search

+4 -5
View File
@@ -3,18 +3,17 @@ Language: Cpp
Standard: Cpp11
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: DontAlign
AlignConsecutiveAssignments: false
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowAllArgumentsOnNextLine: false
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
+4 -18
View File
@@ -1,31 +1,19 @@
---
Checks: "-*,\
modernize-*,\
-modernize-avoid-c-arrays,\
-modernize-make-unique,\
-modernize-raw-string-literal,\
-modernize-use-trailing-return-type,\
-modernize-use-using,\
-modernize-make-unique,\
-modernize-use-trailing-return-type,\
-modernize-avoid-c-arrays,\
performance-*,\
-performance-type-promotion-in-math-fn,\
misc-*,\
-misc-macro-parentheses,\
-misc-misplaced-widening-cast,\
-misc-non-private-member-variables-in-classes,\
-misc-static-assert,\
-misc-unused-parameters,\
readability-*,\
-readability-avoid-const-params-in-decls,\
-readability-else-after-return,\
-readability-function-size,\
-readability-identifier-naming,\
-readability-implicit-bool-conversion,\
-readability-inconsistent-declaration-parameter-name,\
-readability-isolate-declaration,\
-readability-magic-numbers,\
-readability-named-parameter,\
-readability-qualified-auto,\
-readability-uppercase-literal-suffix,\
-misc-non-private-member-variables-in-classes,\
"
WarningsAsErrors: ''
HeaderFilterRegex: 'code/.*$|freespace2/.*$|qtfred/.*$|test/src/.*$|build/.*$'
@@ -35,7 +23,5 @@ CheckOptions:
value: 'assert,Assert,Assertion'
- key: 'modernize-use-emplace.ContainersWithPushBack'
value: 'std::vector;std::deque;std::list;SCP_vector;SCP_deque;SCP_list'
- key: 'readability-braces-around-statements.ShortStatementLines'
value: '4' # Avoid flagging simple if (...) return false; statements
...
-4
View File
@@ -9,7 +9,3 @@ indent_style = tab
[*.{yml,yaml}]
indent_style = space
indent_size = 2
[*.sh]
indent_style = space
indent_size = 4
-8
View File
@@ -1,8 +0,0 @@
cmake/ @asarium
code/executor/ @asarium
code/scpui/ @asarium
code/scripting/ @asarium
-210
View File
@@ -1,210 +0,0 @@
name: Build Nightly package
on:
push:
tags:
- 'nightly_*'
env:
QT_VERSION: 5.12.9
jobs:
build_linux:
strategy:
matrix:
configuration: [FastDebug, Release]
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-a8ca321
steps:
- name: Cache Qt
id: cache-qt-lin
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt
uses: jurplel/install-qt-action@v2
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: |
LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH ninja -k 20 all
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Generate AppImage
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: linux-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/install/*.AppImage
linux_zip:
name: Build Linux distribution zip
needs: build_linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
fetch-depth: '0'
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
- name: Create Distribution package
working-directory: ./builds
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Linux
- name: Upload result package
working-directory: ./builds
env:
INDIEGAMES_USER: ${{ secrets.INDIEGAMES_USER }}
INDIEGAMES_SSHPASS: ${{ secrets.INDIEGAMES_PASSWORD }}
DATACORDER_USER: ${{ secrets.DATACORDER_USER }}
DATACORDER_SSHPASS: ${{ secrets.DATACORDER_PASSWORD }}
run: $GITHUB_WORKSPACE/ci/linux/upload_dist_package.sh nightly
build_windows:
strategy:
matrix:
configuration: [FastDebug, Release]
arch: [Win32, x64]
simd: [SSE2]
name: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Cache Qt
id: cache-qt-win
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-${{ matrix.arch }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt (32 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'Win32' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win32_msvc2017
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Install Qt (64 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'x64' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win64_msvc2017_64
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCHITECTURE: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
shell: bash
run: |
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DFSO_USE_SPEECH="ON" \
-DFSO_USE_VOICEREC="ON" -DMSVC_SIMD_INSTRUCTIONS="$SIMD" \
-DFSO_BUILD_QTFRED=ON -DFSO_BUILD_TESTS=ON \
-DFSO_INSTALL_DEBUG_FILES="ON" -A "$ARCHITECTURE" \
-G "Visual Studio 16 2019" -T "v142" ..
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
shell: bash
run: |
cmake --build . --config "$CONFIGURATION" --target INSTALL -- /verbosity:minimal
ls -alR "$(pwd)/install"
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
windows_zip:
name: Build Windows distribution zip
needs: build_windows
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [Win32, x64]
simd: [SSE2]
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
fetch-depth: '0'
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Create Distribution package
working-directory: ./builds
shell: bash
env:
ARCH: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Windows
- name: Upload result package
working-directory: ./builds
shell: bash
env:
INDIEGAMES_USER: ${{ secrets.INDIEGAMES_USER }}
INDIEGAMES_SSHPASS: ${{ secrets.INDIEGAMES_PASSWORD }}
DATACORDER_USER: ${{ secrets.DATACORDER_USER }}
DATACORDER_SSHPASS: ${{ secrets.DATACORDER_PASSWORD }}
run: $GITHUB_WORKSPACE/ci/linux/upload_dist_package.sh nightly
-263
View File
@@ -1,263 +0,0 @@
name: Build Release package
on:
push:
tags:
- 'release_*'
env:
QT_VERSION: 5.12.9
jobs:
create_release:
name: Create GitHub release
runs-on: ubuntu-latest
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
- name: Store upload URL
run: |
echo -n "${{ steps.create_release.outputs.upload_url }}" > upload_url
- name: Persist upload URL
uses: actions/upload-artifact@v2
with:
name: upload_url
path: ${{ github.workspace }}/upload_url
build_linux:
strategy:
matrix:
configuration: [FastDebug, Release]
name: Linux
needs: create_release
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-a8ca321
steps:
- name: Cache Qt
id: cache-qt-lin
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt
uses: jurplel/install-qt-action@v2
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: |
LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH ninja -k 20 all
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Generate AppImage
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: linux-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/install/*.AppImage
linux_zip:
name: Build Linux distribution zip
needs: build_linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
fetch-depth: '0'
- name: Download upload URL
uses: actions/download-artifact@v1
with:
name: upload_url
path: .
- name: Extract upload URL
id: extractUploadUrl
run: echo "::set-output name=upload_url::$(cat upload_url)"
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
- name: Create Distribution package
id: generate_package
working-directory: ./builds
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Linux
- name: Upload result package
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.extractUploadUrl.outputs.upload_url }}
asset_path: ${{ steps.generate_package.outputs.package_path }}
asset_name: ${{ steps.generate_package.outputs.package_name }}
asset_content_type: ${{ steps.generate_package.outputs.package_mime }}
build_windows:
strategy:
matrix:
configuration: [FastDebug, Release]
arch: [Win32, x64]
simd: [SSE2, AVX]
needs: create_release
name: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Cache Qt
id: cache-qt-win
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-${{ matrix.arch }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt (32 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'Win32' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win32_msvc2017
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Install Qt (64 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'x64' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win64_msvc2017_64
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCHITECTURE: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
shell: bash
run: |
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DFSO_USE_SPEECH="ON" \
-DFSO_USE_VOICEREC="ON" -DMSVC_SIMD_INSTRUCTIONS="$SIMD" \
-DFSO_BUILD_QTFRED=ON -DFSO_BUILD_TESTS=ON \
-DFSO_INSTALL_DEBUG_FILES="ON" -A "$ARCHITECTURE" \
-G "Visual Studio 16 2019" -T "v142" ..
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
shell: bash
run: |
cmake --build . --config "$CONFIGURATION" --target INSTALL -- /verbosity:minimal
ls -alR "$(pwd)/install"
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
windows_zip:
name: Build Windows distribution zip
needs: build_windows
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [Win32, x64]
simd: [SSE2, AVX]
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
fetch-depth: '0'
- name: Download upload URL
uses: actions/download-artifact@v1
with:
name: upload_url
path: .
- name: Extract upload URL
id: extractUploadUrl
run: echo "::set-output name=upload_url::$(cat upload_url)"
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Create Distribution package
id: generate_package
working-directory: ./builds
shell: bash
env:
ARCH: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Windows
- name: Upload result package
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.extractUploadUrl.outputs.upload_url }}
asset_path: ${{ steps.generate_package.outputs.package_path }}
asset_name: ${{ steps.generate_package.outputs.package_name }}
asset_content_type: ${{ steps.generate_package.outputs.package_mime }}
- name: Upload debug symbols
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.extractUploadUrl.outputs.upload_url }}
asset_path: ${{ steps.generate_package.outputs.debug_path }}
asset_name: ${{ steps.generate_package.outputs.debug_name }}
asset_content_type: ${{ steps.generate_package.outputs.debug_mime }}
-224
View File
@@ -1,224 +0,0 @@
name: Build Test package
on:
push:
branches:
- 'test/*'
env:
QT_VERSION: 5.12.9
jobs:
build_linux:
strategy:
matrix:
configuration: [FastDebug, Release]
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-a8ca321
steps:
- name: Cache Qt
id: cache-qt-lin
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt
uses: jurplel/install-qt-action@v2
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Set up test version
shell: bash
run: |
[[ "${{ github.ref }}" =~ ^refs\/heads\/test\/(.*)$ ]]
# Override the revision string so that the builds are named correctly
echo "set(FSO_VERSION_REVISION_STR ${BASH_REMATCH[1]})" > "version_override.cmake"
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: |
LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH ninja -k 20 all
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Generate AppImage
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: linux-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/install/*.AppImage
linux_zip:
name: Build Linux distribution zip
needs: build_linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
steps:
- uses: actions/checkout@v2
name: Checkout
with:
submodules: true
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
- name: Create Distribution package
working-directory: ./builds
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Linux
- name: Upload result package
working-directory: ./builds
env:
INDIEGAMES_USER: ${{ secrets.INDIEGAMES_USER }}
INDIEGAMES_SSHPASS: ${{ secrets.INDIEGAMES_PASSWORD }}
DATACORDER_USER: ${{ secrets.DATACORDER_USER }}
DATACORDER_SSHPASS: ${{ secrets.DATACORDER_PASSWORD }}
run: $GITHUB_WORKSPACE/ci/linux/upload_dist_package.sh test
build_windows:
strategy:
matrix:
configuration: [FastDebug, Release]
arch: [Win32, x64]
simd: [SSE2]
name: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Set up test version
shell: bash
run: |
[[ "${{ github.ref }}" =~ ^refs\/heads\/test\/(.*)$ ]]
# Override the revision string so that the builds are named correctly
echo "set(FSO_VERSION_REVISION_STR ${BASH_REMATCH[1]})" > "version_override.cmake"
- name: Cache Qt
id: cache-qt-win
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-${{ matrix.arch }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt (32 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'Win32' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win32_msvc2017
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Install Qt (64 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.arch == 'x64' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win64_msvc2017_64
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCHITECTURE: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
shell: bash
run: |
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DFSO_USE_SPEECH="ON" \
-DFSO_USE_VOICEREC="ON" -DMSVC_SIMD_INSTRUCTIONS="$SIMD" \
-DFSO_BUILD_QTFRED=ON -DFSO_BUILD_TESTS=ON \
-DFSO_INSTALL_DEBUG_FILES="ON" -A "$ARCHITECTURE" \
-G "Visual Studio 16 2019" -T "v142" ..
- name: Compile
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
shell: bash
run: |
cmake --build . --config "$CONFIGURATION" --target INSTALL -- /verbosity:minimal
ls -alR "$(pwd)/install"
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
windows_zip:
name: Build Windows distribution zip
needs: build_windows
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [Win32, x64]
simd: [SSE2]
steps:
- uses: actions/checkout@v2
name: Checkout
with:
submodules: true
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v1
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Create Distribution package
working-directory: ./builds
shell: bash
env:
ARCH: ${{ matrix.arch }}
SIMD: ${{ matrix.simd }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Windows
- name: Upload result package
working-directory: ./builds
shell: bash
env:
INDIEGAMES_USER: ${{ secrets.INDIEGAMES_USER }}
INDIEGAMES_SSHPASS: ${{ secrets.INDIEGAMES_PASSWORD }}
DATACORDER_USER: ${{ secrets.DATACORDER_USER }}
DATACORDER_SSHPASS: ${{ secrets.DATACORDER_PASSWORD }}
run: $GITHUB_WORKSPACE/ci/linux/upload_dist_package.sh test
+50 -73
View File
@@ -2,73 +2,76 @@ name: Check a pull request
on: [pull_request]
env:
QT_VERSION: 5.12.9
jobs:
build_linux:
strategy:
fail-fast: false
matrix:
configuration: [Debug, Release]
compiler: [gcc-5, gcc-10, clang-9]
cmake_options: [""]
include:
# Also include configurations that check if the code compiles without the graphics backends
- configuration: Debug
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
- configuration: Release
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
compiler: [gcc-5, gcc-9, clang-4.0]
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-e977d36
runs-on: ubuntu-16.04
steps:
- name: Cache Qt
id: cache-qt-lin
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt
uses: jurplel/install-qt-action@v2
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
setup-python: 'false'
- name: Prepare Environment
env:
DEBIAN_FRONTEND: noninteractive
run: |
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo add-apt-repository ppa:beineri/opt-qt571-xenial
sudo add-apt-repository ppa:msulikowski/valgrind # For fixing a bug with valgrind 3.11 which does not recognize the rdrand instruction
sudo apt-get -yq update
sudo apt-get -yq install cmake ninja-build libopenal-dev libreadline6-dev libpng12-dev libjpeg62-dev liblua5.1-0-dev libjansson-dev libsdl2-dev libfreetype6-dev valgrind qt57base g++-5 g++-9 clang-4.0 clang-tidy-4.0 libc++-dev libc++abi-dev
# Fix a header bug present in ubuntu...
sudo ln -s /usr/include/libcxxabi/__cxxabi_config.h /usr/include/c++/v1/__cxxabi_config.h
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
fetch-depth: 0
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
run: |
if [ "$COMPILER" = "gcc-5" ]; then
export CC=gcc-5
export CXX=g++-5
fi
if [ "$COMPILER" = "gcc-9" ]; then
export CC=gcc-9
export CXX=g++-9
fi
if [ "$COMPILER" = "clang-4.0" ]; then
export CC=clang-4.0
export CXX=clang++-4.0
fi
CXXFLAGS="-m64 -mtune=generic -mfpmath=sse -msse -msse2 -pipe -Wno-unknown-pragmas"
CFLAGS="-m64 -mtune=generic -mfpmath=sse -msse -msse2 -pipe -Wno-unknown-pragmas"
if [[ "$CC" =~ ^clang.*$ ]]; then
CXXFLAGS="$CXXFLAGS -stdlib=libc++"
fi
mkdir build
cd build
export CXXFLAGS
export CFLAGS
CMAKE="cmake -G Ninja -DFSO_FATAL_WARNINGS=ON $CMAKE_OPTIONS"
eval $CMAKE -DCMAKE_BUILD_TYPE=$CONFIGURATION -DFSO_BUILD_TESTS=ON -DFSO_BUILD_INCLUDED_LIBS=ON -DFSO_BUILD_QTFRED=ON ..
- name: Compile
working-directory: ./build
run: LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH ninja -k 20 all
run: ninja -k 20 all
- name: Run Tests
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Run Clang Tidy
# Clang-tidy reuses the precompiled headers so this only makes sense for the clang compilers
if: startsWith(matrix.compiler, 'clang-')
run: $GITHUB_WORKSPACE/ci/linux/clang_tidy.sh ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }}
- name: Process clang-tidy warnings
if: startsWith(matrix.compiler, 'clang-')
uses: asarium/clang-tidy-action@v1
with:
fixesFile: clang-fixes.yaml
run: |
if [ "$CONFIGURATION" = "Debug" ]; then
valgrind --leak-check=full --error-exitcode=1 --gen-suppressions=all \
--suppressions="$GITHUB_WORKSPACE/ci/travis/valgrind.supp" ./bin/unittests --gtest_shuffle
else
./bin/unittests --gtest_shuffle
fi
build_windows:
strategy:
matrix:
@@ -84,31 +87,6 @@ jobs:
name: Checkout
with:
submodules: true
- name: Cache Qt
id: cache-qt-win
uses: actions/cache@v1
with:
path: ${{ github.workspace }}/../Qt
key: ${{ runner.os }}-${{ matrix.arch }}-QtCache-${{ env.QT_VERSION }}
- name: Install Qt (32 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.compiler == 'MSVC' && matrix.arch == 'Win32' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win32_msvc2017
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Install Qt (64 bit)
uses: jurplel/install-qt-action@v2
if: ${{ matrix.compiler == 'MSVC' && matrix.arch == 'x64' }}
with:
version: ${{ env.QT_VERSION }}
dir: ${{ github.workspace }}/..
arch: win64_msvc2017_64
cached: ${{ steps.cache-qt-win.outputs.cache-hit }}
aqtversion: ==0.8
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
@@ -124,8 +102,7 @@ jobs:
-DFSO_BUILD_FRED2="OFF" -DCMAKE_BUILD_TYPE=$CONFIGURATION -G "Ninja" ..
else
cmake -DFSO_USE_SPEECH="ON" -DFSO_FATAL_WARNINGS="ON" -DFSO_USE_VOICEREC="OFF" -DFSO_BUILD_TESTS="ON" \
-DMSVC_SIMD_INSTRUCTIONS=SSE2 -DFSO_BUILD_FRED2="ON" -G "Visual Studio 16 2019" \
-DFSO_BUILD_QTFRED=ON -T "v142" -A "$ARCHITECTURE" ..
-DMSVC_SIMD_INSTRUCTIONS=SSE2 -DFSO_BUILD_FRED2="ON" -G "Visual Studio 16 2019" -T "v142" -A "$ARCHITECTURE" ..
fi
- name: Compile
working-directory: ./build
+28 -2
View File
@@ -86,6 +86,19 @@ matrix:
packages:
- g++-9
- *global_deps
- os: linux
env: CONFIGURATION="Debug" CC=clang-4.0 CXX=clang++-4.0 CMAKE_OPTIONS="-DCLANG_USE_LIBCXX=ON"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-xenial-8
- sourceline: 'ppa:beineri/opt-qt571-xenial'
packages:
- *global_deps
- clang-4.0
- libc++-dev
- libc++abi-dev
- os: linux
env: CONFIGURATION="Debug" CC=clang-9 CXX=clang++-9 CMAKE_OPTIONS="-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"
addons:
@@ -103,7 +116,7 @@ matrix:
env: CONFIGURATION="Debug"
- os: windows
env: CONFIGURATION="Debug" CMAKE_TOOLSET=v141 CMAKE_GENERATOR="Visual Studio 15 2017"
env: CONFIGURATION="Debug" CMAKE_TOOLSET=v141_xp CMAKE_GENERATOR="Visual Studio 15 2017"
- os: windows
env: CONFIGURATION="Debug" CMAKE_TOOLSET="" CMAKE_GENERATOR="Ninja"
@@ -127,6 +140,19 @@ matrix:
packages:
- g++-9
- *global_deps
- os: linux
env: CONFIGURATION="Release" CC=clang-4.0 CXX=clang++-4.0 CMAKE_OPTIONS="-DCLANG_USE_LIBCXX=ON"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-xenial-8
- sourceline: 'ppa:beineri/opt-qt571-xenial'
packages:
- *global_deps
- clang-4.0
- libc++-dev
- libc++abi-dev
- os: linux
env: CONFIGURATION="Release" CC=clang-9 CXX=clang++-9 CMAKE_OPTIONS="-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"
addons:
@@ -144,7 +170,7 @@ matrix:
env: CONFIGURATION="Release"
- os: windows
env: CONFIGURATION="Release" CMAKE_TOOLSET=v141 CMAKE_GENERATOR="Visual Studio 15 2017"
env: CONFIGURATION="Release" CMAKE_TOOLSET=v141_xp CMAKE_GENERATOR="Visual Studio 15 2017"
- os: windows
env: CONFIGURATION="Release" CMAKE_TOOLSET="" CMAKE_GENERATOR="Ninja"
# There is a GCC compiler bug with MinGW that causes compilation failures on Windows at the moment
+3 -19
View File
@@ -8,7 +8,6 @@ if ("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}")
endif()
include(cmake/util.cmake)
include(cmake/embed_file.cmake)
# Set a few policies
set_policy(CMP0051 NEW)
@@ -44,14 +43,9 @@ PROJECT(FS2_Open)
find_program(CCACHE_PROGRAM ccache)
# Currently only GCC support ccache properly without generating additional warnings
if(CCACHE_PROGRAM AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
if(NOT CMAKE_C_COMPILER_LAUNCHER)
message(STATUS "Using ccache for C compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
endif()
if(NOT CMAKE_CXX_COMPILER_LAUNCHER)
message(STATUS "Using ccache for C++ compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
endif()
message(STATUS "Using ccache for compilation: ${CCACHE_PROGRAM}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE_PROGRAM}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "${CCACHE_PROGRAM}")
endif()
IF(CMAKE_CROSSCOMPILING)
@@ -127,10 +121,6 @@ option(FSO_RELEASE_LOGGING "Enable logging output for release builds" OFF)
OPTION(FSO_BUILD_WITH_FFMPEG "Enable the usage of FFmpeg for sound and custscenes" ON)
OPTION(FSO_BUILD_WITH_OPENGL "Enable compilation of the OpenGL renderer" ON)
OPTION(FSO_BUILD_WITH_VULKAN "Enable compilation of the Vulkan renderer" ON)
MARK_AS_ADVANCED(FORCE FSO_CMAKE_DEBUG)
MARK_AS_ADVANCED(FORCE FSO_BUILD_INCLUDED_LIBS)
MARK_AS_ADVANCED(FORCE FSO_USE_OPENALSOFT)
@@ -141,8 +131,6 @@ mark_as_advanced(FORCE FSO_INSTALL_DEBUG_FILES)
mark_as_advanced(FORCE ENABLE_COTIRE)
mark_as_advanced(FORCE FSO_RELEASE_LOGGING)
mark_as_advanced(FORCE FSO_BUILD_WITH_FFMPEG)
mark_as_advanced(FORCE FSO_BUILD_WITH_OPENGL)
mark_as_advanced(FORCE FSO_BUILD_WITH_VULKAN)
# Include cotire file from https://github.com/sakra/cotire/
include(cotire)
@@ -169,8 +157,6 @@ ADD_SUBDIRECTORY(tools)
ADD_SUBDIRECTORY(lib)
ADD_SUBDIRECTORY(parsers)
ADD_SUBDIRECTORY(code)
ADD_SUBDIRECTORY(freespace2)
@@ -219,5 +205,3 @@ message(STATUS "Building qtFRED: ${FSO_BUILD_QTFRED}")
message(STATUS "Fatal warnings: ${FSO_FATAL_WARNINGS}")
message(STATUS "Release logging: ${FSO_RELEASE_LOGGING}")
message(STATUS "With FFmpeg: ${FSO_BUILD_WITH_FFMPEG}")
message(STATUS "With OpenGL: ${FSO_BUILD_WITH_OPENGL}")
message(STATUS "With Vulkan: ${FSO_BUILD_WITH_VULKAN}")
-7
View File
@@ -12,11 +12,4 @@ Modifications by members of the FreeSpace Source Code Project are
released under whatever terms the individual authors choose, but the
above notice continues to apply to all fs2_open code.
All modifications made on or after November 1, 2020, shall be released under
the terms within [Unlicense](Unlicense.md). Modifications made before said date are released
under the previous terms with the exception of modifications made by members
of the FreeSpace Source Code Project that opt-in to the terms of Unlicense. Additionally,
a list of contributors who have opted in to the Unlicense terms can be found
in [**Licensing**](https://github.com/scp-fs2open/fs2open.github.com/wiki/Licensing).
See [**Licensing**](https://github.com/scp-fs2open/fs2open.github.com/wiki/Licensing) for more information.
-24
View File
@@ -1,24 +0,0 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to [**Unlicense**](https://unlicense.org).
+2 -2
View File
@@ -8,11 +8,11 @@ environment:
matrix:
- BuildID: 0
CMAKE_GENERATOR: Visual Studio 14 2015
PlatformToolset: v140
PlatformToolset: v140_xp
QT_DIR: C:\Qt\5.9\msvc2015
- BuildID: 1
CMAKE_GENERATOR: Visual Studio 14 2015 Win64
PlatformToolset: v140
PlatformToolset: v140_xp
QT_DIR: C:\Qt\5.9\msvc2015_64
before_build:
- git submodule update --init --recursive
+48 -48
View File
@@ -9,56 +9,56 @@ class BuildConfig {
}
$NightlyConfigurations = @(
# [BuildConfig]@{
# Generator="Visual Studio 14 2015 Win64";
# PackageType="Win64";
# Toolset="v140";
# SimdType="SSE2";
# QtDir="C:\Qt\5.9\msvc2015_64";
# SourcePackage=$false;
# },
# [BuildConfig]@{
# Generator="Visual Studio 14 2015";
# PackageType="Win32";
# Toolset="v140";
# SimdType="SSE2";
# QtDir="C:\Qt\5.9\msvc2015";
# SourcePackage=$false;
# }
[BuildConfig]@{
Generator="Visual Studio 14 2015 Win64";
PackageType="Win64";
Toolset="v140_xp";
SimdType="SSE2";
QtDir="C:\Qt\5.9\msvc2015_64";
SourcePackage=$false;
},
[BuildConfig]@{
Generator="Visual Studio 14 2015";
PackageType="Win32";
Toolset="v140_xp";
SimdType="SSE2";
QtDir="C:\Qt\5.9\msvc2015";
SourcePackage=$false;
}
)
$ReleaseConfigurations = @(
# [BuildConfig]@{
# Generator="Visual Studio 14 2015";
# PackageType="Win32";
# Toolset="v140";
# SimdType="SSE2";
# QtDir="C:\Qt\5.9\msvc2015";
# SourcePackage=$true;
# }
# [BuildConfig]@{
# Generator="Visual Studio 14 2015";
# PackageType="Win32-AVX";
# Toolset="v140";
# SimdType="AVX";
# QtDir="C:\Qt\5.9\msvc2015";
# SourcePackage=$false;
# }
# [BuildConfig]@{
# Generator="Visual Studio 14 2015 Win64";
# PackageType="Win64";
# Toolset="v140";
# SimdType="SSE2";
# QtDir="C:\Qt\5.9\msvc2015_64";
# SourcePackage=$false;
# }
# [BuildConfig]@{
# Generator="Visual Studio 14 2015 Win64";
# PackageType="Win64-AVX";
# Toolset="v140";
# SimdType="AVX";
# QtDir="C:\Qt\5.9\msvc2015_64";
# SourcePackage=$false;
# }
[BuildConfig]@{
Generator="Visual Studio 14 2015";
PackageType="Win32";
Toolset="v140_xp";
SimdType="SSE2";
QtDir="C:\Qt\5.9\msvc2015";
SourcePackage=$true;
}
[BuildConfig]@{
Generator="Visual Studio 14 2015";
PackageType="Win32-AVX";
Toolset="v140_xp";
SimdType="AVX";
QtDir="C:\Qt\5.9\msvc2015";
SourcePackage=$false;
}
[BuildConfig]@{
Generator="Visual Studio 14 2015 Win64";
PackageType="Win64";
Toolset="v140_xp";
SimdType="SSE2";
QtDir="C:\Qt\5.9\msvc2015_64";
SourcePackage=$false;
}
[BuildConfig]@{
Generator="Visual Studio 14 2015 Win64";
PackageType="Win64-AVX";
Toolset="v140_xp";
SimdType="AVX";
QtDir="C:\Qt\5.9\msvc2015_64";
SourcePackage=$false;
}
)
$BuildConfigurations = $null
-23
View File
@@ -1,23 +0,0 @@
#!/usr/bin/env bash
set -e
SCRIPT=$(readlink -f "$0")
HERE=$(dirname "$SCRIPT")
COMMIT_RANGE=$1..$2
if ! git rev-list $COMMIT_RANGE 2>&1 >/dev/null; then
echo "\$COMMIT_RANGE ($COMMIT_RANGE) is not valid for this build (probably caused by a rebase)."
exit 0
fi
# In order to get a proper diff without irrelevant changes, we need to determine where we branched off from the base
# branch
BASE_COMMIT=$(git merge-base $1 $2)
echo "Running clang-tidy on changed files"
git diff -U0 --no-color "$BASE_COMMIT..$2" | \
$HERE/clang-tidy-diff.py -path "$(pwd)/build" -p1 \
-regex '(code(?!\/graphics\/shaders\/compiled)|freespace2|qtfred|test|build|tools)\/.*\.(cpp|h)' \
-clang-tidy-binary /usr/bin/clang-tidy-9 -j$(nproc) -export-fixes "$(pwd)/clang-fixes.yaml"
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
if [ "$COMPILER" = "gcc-5" ]; then
export CC=gcc-5
export CXX=g++-5
fi
if [ "$COMPILER" = "gcc-10" ]; then
export CC=gcc-10
export CXX=g++-10
fi
if [ "$COMPILER" = "clang-9" ]; then
# Work around bug in clang that uses the wrong installation directory: https://bugs.llvm.org/show_bug.cgi?id=47460
export CC=$(readlink -f $(which clang-9))
export CXX=$(readlink -f $(which clang++-9))
fi
LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH
CXXFLAGS="-m64 -mtune=generic -mfpmath=sse -msse -msse2 -pipe -Wno-unknown-pragmas"
CFLAGS="-m64 -mtune=generic -mfpmath=sse -msse -msse2 -pipe -Wno-unknown-pragmas"
CMAKE_OPTIONS="$JOB_CMAKE_OPTIONS"
if [[ "$COMPILER" =~ ^clang.*$ ]]; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCLANG_USE_LIBCXX=ON"
fi
mkdir build
cd build
export CXXFLAGS
export CFLAGS
export LD_LIBRARY_PATH
cmake -G Ninja -DFSO_FATAL_WARNINGS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON $CMAKE_OPTIONS \
-DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DFSO_BUILD_APPIMAGE=ON -DCMAKE_BUILD_TYPE=$CONFIGURATION \
-DFFMPEG_USE_PRECOMPILED=ON -DFSO_BUILD_TESTS=ON -DFSO_BUILD_INCLUDED_LIBS=ON -DFSO_BUILD_QTFRED=ON \
-DSHADERS_ENABLE_COMPILATION=ON ..
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
SCRIPT=$(readlink -f "$0")
HERE=$(dirname "$SCRIPT")
OS="$1"
source $HERE/dist_functions.sh
if [ "$OS" = "Linux" ]; then
tar -cvzf "$(get_package_name)-builds-Linux.tar.gz" *
echo "::set-output name=package_path::$(pwd)/$(get_package_name)-builds-Linux.tar.gz"
echo "::set-output name=package_name::$(get_package_name)-builds-Linux.tar.gz"
echo "::set-output name=package_mime::$(file -b --mime-type "$(pwd)/$(get_package_name)-builds-Linux.tar.gz")"
elif [ "$OS" = "Windows" ]; then
7z a -xr'!*.pdb' "$(get_package_name)-builds-$ARCH-$SIMD.zip" "*"
echo "::set-output name=package_path::$(pwd)/$(get_package_name)-builds-$ARCH-$SIMD.zip"
echo "::set-output name=package_name::$(get_package_name)-builds-$ARCH-$SIMD.zip"
echo "::set-output name=package_mime::$(file -b --mime-type "$(pwd)/$(get_package_name)-builds-$ARCH-$SIMD.zip")"
7z a "$(get_package_name)-debug-$ARCH-$SIMD.7z" "*.pdb"
echo "::set-output name=debug_path::$(pwd)/$(get_package_name)-debug-$ARCH-$SIMD.7z"
echo "::set-output name=debug_name::$(get_package_name)-debug-$ARCH-$SIMD.7z"
echo "::set-output name=debug_mime::$(file -b --mime-type "$(pwd)/$(get_package_name)-debug-$ARCH-$SIMD.7z")"
else
echo "Invalid OS: $OS"
fi
-70
View File
@@ -1,70 +0,0 @@
function get_package_name() {
if git describe --match 'nightly_*' --exact-match 2>/dev/null >/dev/null; then
echo -n "$(git describe --match "nightly_*" --exact-match)"
return
fi
if git describe --match 'release_*' --exact-match 2>/dev/null >/dev/null; then
echo -n "$(git describe --match "release_*" --exact-match | sed 's/release_/fs2_open_/i')"
return
fi
if [[ "$(git branch --show-current)" =~ ^test\/(.*)$ ]]; then
echo -n "test_${BASH_REMATCH[1]}"
return
fi
echo "unknown_config"
}
function get_version_name() {
if git describe --match 'nightly_*' --exact-match 2>/dev/null >/dev/null; then
local tag_name=$(git describe --match "nightly_*" --exact-match)
# Use the bash regex matching for getting the relevant part of the tag name
[[ $tag_name =~ ^nightly_(.*)$ ]]
echo -n "${BASH_REMATCH[1]}"
return
fi
if git describe --match 'release_*' --exact-match 2>/dev/null >/dev/null; then
local tag_name=$(git describe --match "release_*" --exact-match)
# Use the bash regex matching for getting the relevant part of the tag name
[[ $tag_name =~ ^release_(.*)$ ]]
echo -n "${BASH_REMATCH[1]}"
return
fi
if [[ "$(git branch --show-current)" =~ ^test\/(.*)$ ]]; then
echo -n "${BASH_REMATCH[1]}"
return
fi
echo "unknown_config"
}
function upload_files_to_sftp() {
# We need empty glob patterns to "disappear" in the for loop below since this will be run for different configurations
# where it may be possible that some of the file patterns will not be present
shopt -s nullglob
echo "cd $2/" > sftp_batch
echo "mkdir $(get_version_name)" >> sftp_batch
# Create directory but do not cause an error if it already exists
sshpass -e sftp -oBatchMode=no -o "StrictHostKeyChecking no" -b sftp_batch $1 || true
echo "cd $2/$(get_version_name)/" > sftp_batch
for file in *.tar.gz *.7z *.zip; do
echo "put $file" >> sftp_batch
done
echo "bye" >> sftp_batch
sshpass -e sftp -oBatchMode=no -o "StrictHostKeyChecking no" -b sftp_batch $1
rm sftp_batch
}
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bash
INSTALL_FOLDER=$1
# Install Freespace2 targets
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_FOLDER -DCOMPONENT=Unspecified -P cmake_install.cmake
cmake -DCMAKE_INSTALL_PREFIX=$INSTALL_FOLDER -DCOMPONENT=Freespace2 -P cmake_install.cmake
# We need to be a bit creative for determining the AppImage name since we don't want to hard-code the name
FILENAME="$(find $INSTALL_FOLDER/bin -name 'fs2_open_*' -type f -printf "%f\n").AppImage"
appimagetool -n $INSTALL_FOLDER "$INSTALL_FOLDER/$FILENAME"
chmod +x "$INSTALL_FOLDER/$FILENAME"
ls -al $INSTALL_FOLDER
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env bash
SCRIPT=$(readlink -f "$0")
HERE=$(dirname "$SCRIPT")
export LD_LIBRARY_PATH=$(pwd)/bin/lib:$LD_LIBRARY_PATH
if [ "$CONFIGURATION" = "Debug" ]; then
valgrind --leak-check=full --error-exitcode=1 --gen-suppressions=all \
--suppressions="$HERE/valgrind.supp" ./bin/unittests --gtest_shuffle
else
./bin/unittests --gtest_shuffle
fi
-21
View File
@@ -1,21 +0,0 @@
#!/usr/bin/env bash
set -e
UPLOAD_TYPE=$1
SCRIPT=$(readlink -f "$0")
HERE=$(dirname "$SCRIPT")
source $HERE/dist_functions.sh
if [ "$UPLOAD_TYPE" = "nightly" ]; then
SSHPASS=$INDIEGAMES_SSHPASS upload_files_to_sftp "$INDIEGAMES_USER@scp.indiegames.us" "public_html/builds/nightly"
SSHPASS=$DATACORDER_SSHPASS upload_files_to_sftp "$DATACORDER_USER@porphyrion.feralhosting.com" "www/datacorder.porphyrion.feralhosting.com/public_html/builds/nightly"
elif [ "$UPLOAD_TYPE" = "test" ]; then
SSHPASS=$DATACORDER_SSHPASS upload_files_to_sftp "$DATACORDER_USER@porphyrion.feralhosting.com" "www/datacorder.porphyrion.feralhosting.com/public_html/builds/test"
else
echo "Unknown upload type $UPLOAD_TYPE"
exit 1
fi
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env python
#
#===- clang-tidy-diff.py - ClangTidy Diff Checker ------------*- python -*--===#
#
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -e
if ! git rev-list $TRAVIS_COMMIT_RANGE 2>1 >/dev/null; then
echo "\$TRAVIS_COMMIT_RANGE ($TRAVIS_COMMIT_RANGE) is not valid for this build (probably caused by a rebase)."
exit 0
fi
cd "$TRAVIS_BUILD_DIR"
echo "Running clang-tidy on changed files"
git diff -U0 --no-color $TRAVIS_COMMIT_RANGE | \
$TRAVIS_BUILD_DIR/ci/travis/clang-tidy-diff.py -path "$TRAVIS_BUILD_DIR/build" -p1 \
-regex '(code|freespace2|qtfred|testsrc|build|tools)\/.*\.(cpp|h)' \
-clang-tidy-binary /usr/bin/clang-tidy-9 -j$(nproc) -quiet 2>/dev/null | \
tee clang-tidy-output.txt
if [[ -n $(grep "warning: " clang-tidy-output.txt) ]] || [[ -n $(grep "error: " clang-tidy-output.txt) ]]; then
echo "Errors or warnings were detected in the clang-tidy output!"
exit 1
else
echo -e "\033[1;32m\xE2\x9C\x93 passed:\033[0m clang-tidy test succeeded";
fi
+1 -1
View File
@@ -18,7 +18,7 @@ elif [ "$TRAVIS_OS_NAME" = "osx" ]; then
XCODE_RET=${PIPESTATUS[0]}
if [ "$XCODE_RET" -ne "0" ]; then
tar -cvzf build.log.tar.gz build.log
curl --upload-file build.log.tar.gz "https://keep.sh"
curl --upload-file build.log.tar.gz "https://transfer.sh/build.log.tar.gz"
exit $XCODE_RET
fi
elif [ "$TRAVIS_OS_NAME" = "windows" ]; then
@@ -145,19 +145,20 @@
fun:dl_open_worker
}
{
dlopen leak
<insert_a_suppression_name_here>
Memcheck:Leak
match-leak-kinds: definite
fun:malloc
fun:_dl_exception_create
fun:_dl_signal_error
fun:_dl_map_object
fun:dl_open_worker
fun:_dl_catch_exception
fun:_dl_open
fun:dlopen_doit
fun:_dl_catch_exception
fun:_dl_catch_error
fun:_dlerror_run
fun:dlopen@@GLIBC_2.2.5
obj:*
obj:*
fun:call_init.part.0
fun:call_init
fun:_dl_init
fun:dl_open_worker
}
+2
View File
@@ -4,6 +4,8 @@ include(WriteCompilerDetectionHeader)
set(CMAKE_CXX_STANDARD_REQUIRED 11)
set(CMAKE_CXX_STANDARD 11)
set(REQUIRED_CXX_FEATURES cxx_rvalue_references cxx_nullptr)
get_property(CMAKE_CXX_KNOWN_FEATURES GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)
write_compiler_detection_header(
-114
View File
@@ -1,114 +0,0 @@
set(_EMBEDD_FILE_BASE_DIR "${CMAKE_CURRENT_LIST_DIR}")
function(target_embed_files _target)
set(options)
set(oneValueArgs RELATIVE_TO PATH_TYPE_PREFIX)
set(multiValueArgs FILES)
cmake_parse_arguments(EMBED "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if (NOT DEFINED EMBED_RELATIVE_TO)
set(EMBED_RELATIVE_TO "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
if (NOT IS_ABSOLUTE "${EMBED_RELATIVE_TO}")
get_filename_component(EMBED_RELATIVE_TO "${EMBED_RELATIVE_TO}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
foreach (file ${EMBED_FILES})
get_filename_component(_absoluteFile "${file}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
file(RELATIVE_PATH _pathType "${EMBED_RELATIVE_TO}" "${_absoluteFile}")
get_filename_component(_pathType ${_pathType} DIRECTORY)
if (DEFINED EMBED_PATH_TYPE_PREFIX)
if (_pathType)
set(_pathType "${EMBED_PATH_TYPE_PREFIX}/${_pathType}")
else()
# Avoid trailing / when we are in the same directory
set(_pathType "${EMBED_PATH_TYPE_PREFIX}")
endif()
endif()
if (NOT _pathType)
# If it is still empty then we need to work around yet another annoying CMake behavior where it ignores
# "empty" property strings
set(_pathType ".")
endif()
set_property(TARGET ${_target} APPEND PROPERTY EMBEDDED_FILES "${_absoluteFile}")
set_property(TARGET ${_target} APPEND PROPERTY EMBEDDED_FILES_BASE_DIR "${EMBED_RELATIVE_TO}")
set_property(TARGET ${_target} APPEND PROPERTY EMBEDDED_FILES_PATH_TYPE "${_pathType}")
endforeach()
endfunction()
function(handle_embedded_files _target)
get_target_property(_filesToEmbed ${_target} EMBEDDED_FILES)
get_target_property(_baseDirs ${_target} EMBEDDED_FILES_BASE_DIR)
get_target_property(_pathTypes ${_target} EMBEDDED_FILES_PATH_TYPE)
SET(DEF_OUT_FILES)
set(INCLUDE_LIST)
set(ARRAY_ELEMENTS)
list(LENGTH _filesToEmbed _numFiles)
FOREACH(i RANGE ${_numFiles})
# Why must CMake always do the unexpected thing? The foreach variant includes the last index as opposed to every
# other sensible language which does not include it...
if (i GREATER_EQUAL _numFiles)
break()
endif()
list(GET _filesToEmbed ${i} _filePath)
list(GET _baseDirs ${i} _baseDir)
list(GET _pathTypes ${i} _pathType)
if (_pathType STREQUAL ".")
# Handle the workaround we had to do for empty path types
set(_pathType "")
endif()
file(RELATIVE_PATH _relativeFilePath "${_baseDir}" "${_filePath}")
SET(_outputBasePath "${CMAKE_CURRENT_BINARY_DIR}/embedded_files/${_relativeFilePath}")
# For some reason this is needed...
get_filename_component(_outputDirectory ${_outputBasePath} DIRECTORY)
file(MAKE_DIRECTORY ${_outputDirectory})
# Retrieve the path type name from the relative path
file(TO_NATIVE_PATH "${_pathType}" _pathType)
if (MINGW)
# There is a bug in CMake where it thinks MinGW uses forward slashes for paths but we need backslashes for Windows builds
string(REPLACE "/" "\\" _pathType "${_pathType}")
endif()
# Properly escape back slashes in strings
string(REPLACE "\\" "\\\\" _pathType "${_pathType}")
get_filename_component(FILE_NAME "${_relativeFilePath}" NAME)
string(MAKE_C_IDENTIFIER "${_relativeFilePath}" FIELD_NAME)
set(HEADER_FILE "${_outputBasePath}.h")
set(SOURCE_FILE "${_outputBasePath}.cpp")
set(ALL_OUTPUTS "${HEADER_FILE}" "${SOURCE_FILE}")
set(FIELD_NAME "Embedded_${FIELD_NAME}")
set(INCLUDE_LIST "${INCLUDE_LIST}\n#include \"${HEADER_FILE}\"")
set(ARRAY_ELEMENTS "${ARRAY_ELEMENTS}\n\t{ \"${_pathType}\", \"${FILE_NAME}\" , ${FIELD_NAME} , ${FIELD_NAME}_size },")
add_custom_command(
OUTPUT ${ALL_OUTPUTS}
COMMAND embedfile "${_filePath}" "${_outputBasePath}" "${FIELD_NAME}"
MAIN_DEPENDENCY "${_filePath}"
COMMENT "Generating string file for ${_filePath}"
)
list(APPEND DEF_OUT_FILES ${ALL_OUTPUTS})
ENDFOREACH()
configure_file("${_EMBEDD_FILE_BASE_DIR}/embedded_files.inc.in" "${CMAKE_CURRENT_BINARY_DIR}/embedded_files/embedded_files.inc")
target_include_directories(${_target} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/embedded_files")
target_sources(${_target} PRIVATE ${DEF_OUT_FILES})
source_group("Generated Files\\Embedded Files" FILES ${DEF_OUT_FILES})
endfunction()
+2 -2
View File
@@ -20,8 +20,8 @@ target_link_libraries(platform INTERFACE ${WIN32_LIBS})
target_compile_definitions(platform INTERFACE WIN32 USE_OPENAL _WINDOWS)
# Specify minimum Windows version for the headers (currently this is Vista)
target_compile_definitions(platform INTERFACE NTDDI_VERSION=0x06000000 _WIN32_WINNT=0x0600)
# Specify minimum Windows version for the headers (currently this is XP)
target_compile_definitions(platform INTERFACE NTDDI_VERSION=0x05010000 _WIN32_WINNT=0x0501)
SET(EXE_GUI_TYPE WIN32)
set(PLATFORM_WINDOWS TRUE CACHE INTERNAL "" FORCE)
+1
View File
@@ -42,6 +42,7 @@ CHECK_FUNCTION_EXISTS(strlwr SCP_HAVE_STRLWR)
CHECK_INCLUDE_FILE("strings.h" SCP_HAVE_STRINGS_H)
check_symbol_exists(snprintf "stdio.h" SCP_HAVE_SNPRINTF)
check_symbol_exists(_snprintf "stdio.h" SCP_HAVE__SNPRINTF)
set(PLATFORM_CHECK_HEADER "${GENERATED_SOURCE_DIR}/platformChecks.h")
CONFIGURE_FILE(${CMAKE_CURRENT_LIST_DIR}/platformChecks.h.in "${PLATFORM_CHECK_HEADER}")
-12
View File
@@ -23,7 +23,6 @@ endif()
if (CLANG_USE_LIBCXX)
set(CXX_BASE_FLAGS "${CXX_BASE_FLAGS} -stdlib=libc++")
target_link_libraries(compiler INTERFACE "c++" "c++abi")
endif()
# Initialize with an empty string to make sure we always get a clean start
@@ -118,14 +117,3 @@ endif()
# Always define this to make sure that the fixed width format macros are available
target_compile_definitions(compiler INTERFACE __STDC_FORMAT_MACROS)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux" OR MINGW)
# GNU ar: Create thin archive files.
# Requires binutils-2.19 or later.
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> qcTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> qTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qcTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> qTP <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
target_link_libraries(compiler INTERFACE m)
+8 -39
View File
@@ -8,8 +8,6 @@ MESSAGE(STATUS "Doing configuration specific to gcc...")
option(GCC_ENABLE_LEAK_CHECK "Enable -fsanitize=leak" OFF)
option(GCC_ENABLE_ADDRESS_SANITIZER "Enable -fsanitize=address" OFF)
option(GCC_ENABLE_SANITIZE_UNDEFINED "Enable -fsanitize=undefined" OFF)
option(GCC_USE_GOLD "Use the gold linker instead of the standard linker" OFF)
option(GCC_GENERATE_GDB_INDEX "Adds linker option to generate the gdb index for debug builds" OFF)
# These are the default values
set(C_BASE_FLAGS "-march=native -pipe")
@@ -25,16 +23,6 @@ endif()
# Initialize with an empty string to make sure we always get a clean start
set(COMPILER_FLAGS "")
set(LINKER_FLAGS "")
if (GCC_USE_GOLD)
OPTION(GCC_INCREMENTAL_LINKING "Use incremental linking" OFF)
set(LINKER_FLAGS "${LINKER_FLAGS} -fuse-ld=gold")
if (GCC_INCREMENTAL_LINKING)
set(LINKER_FLAGS "${LINKER_FLAGS} -fno-use-linker-plugin -Wl,-z,norelro -Wl,--incremental")
endif()
endif()
# This is a slight hack since our flag setup is a bit more complicated
_enable_extra_compiler_warnings_flags()
@@ -42,11 +30,9 @@ set(COMPILER_FLAGS "${COMPILER_FLAGS} ${_flags}")
set(COMPILER_FLAGS "${COMPILER_FLAGS} -funroll-loops -fsigned-char -Wno-unknown-pragmas")
if (NOT GCC_INCREMENTAL_LINKING)
# Place each function and data in its own section so the linker can
# perform dead code elimination
set(COMPILER_FLAGS "${COMPILER_FLAGS} -fdata-sections -ffunction-sections")
endif()
# Place each function and data in its own section so the linker can
# perform dead code elimination
set(COMPILER_FLAGS "${COMPILER_FLAGS} -fdata-sections -ffunction-sections")
if ("${CMAKE_GENERATOR}" STREQUAL "Ninja")
# Force color diagnostics for Ninja generator
@@ -112,7 +98,7 @@ set(COMPILER_FLAGS_RELEASE "-O2 -Wno-unused-variable -Wno-unused-but-set-variabl
set(COMPILER_FLAGS_DEBUG "-O0 -g -Wshadow")
# Always use the base flags and add our compiler flags at the back
# Always use the base flags and add our compiler flags at the bacl
set(CMAKE_CXX_FLAGS "${CXX_BASE_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_C_FLAGS "${C_BASE_FLAGS} ${COMPILER_FLAGS}")
@@ -122,7 +108,7 @@ set(CMAKE_C_FLAGS_RELEASE ${COMPILER_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_C_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_EXE_LINKER_FLAGS "${LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "")
IF (MINGW)
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static -static-libgcc -static-libstdc++ -Wl,--enable-auto-import")
@@ -135,25 +121,17 @@ endif()
set(CMAKE_EXE_LINKER_FLAGS_RELEASE "")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "-g")
if (GCC_GENERATE_GDB_INDEX)
# For pure debug binaries, generate a gdb index for better debugging
SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -Wl,--gdb-index")
endif()
IF(NOT MINGW)
SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -rdynamic")
# Allow the linker to perform dead code elimination; this is considered
# experimental for COFF and PE formats and thus disabled for Windows builds
# (https://sourceware.org/binutils/docs/ld/Options.html)
if (NOT GCC_INCREMENTAL_LINKING AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections")
endif()
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections")
ENDIF(NOT MINGW)
IF(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-zignore")
ENDIF()
SET(CMAKE_EXE_LINKER_FLAGS "-Wl,-zignore")
ENDIF(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
if (FSO_FATAL_WARNINGS)
# Make warnings fatal if the right variable is set
@@ -162,12 +140,3 @@ endif()
# Always define this to make sure that the fixed width format macros are available
target_compile_definitions(compiler INTERFACE __STDC_FORMAT_MACROS=1)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux" OR MINGW)
# GNU ar: Create thin archive files.
# Requires binutils-2.19 or later.
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> qcTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> qTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qcTP <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> qTP <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
-3
View File
@@ -17,9 +17,6 @@ ELSE("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
MESSAGE(STATUS "No special handling for this compiler present, good luck!")
ENDIF("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
find_package(Threads REQUIRED)
target_link_libraries(compiler INTERFACE Threads::Threads)
# Copy release settings to FastDebug
set(CMAKE_C_FLAGS_FASTDEBUG "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_FASTDEBUG "${CMAKE_CXX_FLAGS_RELEASE}")
+7 -43
View File
@@ -140,34 +140,14 @@ macro(set_if_not_defined VAR VALUE)
endif()
endmacro(set_if_not_defined)
function(set_precompiled_header _target _headerPath)
if (COMMAND target_precompile_headers)
target_compile_definitions(${_target} PRIVATE CMAKE_PCH)
target_precompile_headers(${_target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${_headerPath}>")
else()
if (ENABLE_COTIRE)
message("${_headerPath}")
set_target_properties(${_target} PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "${_headerPath}")
macro(configure_cotire target)
if(ENABLE_COTIRE)
# Disable unity build as it doesn't work well for us
set_target_properties(${target} PROPERTIES COTIRE_ADD_UNITY_BUILD FALSE)
# Disable unity build as it doesn't work well for us
set_target_properties(${_target} PROPERTIES COTIRE_ADD_UNITY_BUILD FALSE)
cotire(${_target})
else()
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
target_compile_options(${_target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${_headerPath}>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
target_compile_options(${_target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:/FI ${_headerPath}>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
target_compile_options(${_target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${_headerPath}>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
target_compile_options(${_target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${_headerPath}>")
ELSE()
MESSAGE("Unknown compiler for global includes. This will probably break the build.")
ENDIF()
endif()
cotire(${target})
endif()
endfunction()
endmacro(configure_cotire)
macro(add_target_copy_files)
foreach(file ${ARGN})
@@ -204,7 +184,7 @@ function(detect_simd_instructions _out_var)
endfunction()
function (check_linker_flag _flag _out_var)
SET(CMAKE_REQUIRED_LINK_OPTIONS "${_flag}")
SET(CMAKE_REQUIRED_FLAGS "${_flag}")
CHECK_C_COMPILER_FLAG("" ${_out_var})
endfunction(check_linker_flag)
@@ -218,22 +198,6 @@ function(suppress_warnings _target)
endif()
endfunction(suppress_warnings)
# Suppresses warnings for the specified files
function(suppress_file_warnings)
if (MSVC)
set_source_files_properties(
${ARGN}
PROPERTIES
COMPILE_FLAGS "/W0")
else()
# Assume everything else uses GCC style options
set_source_files_properties(
${ARGN}
PROPERTIES
COMPILE_FLAGS "-w")
endif()
endfunction(suppress_file_warnings)
function(list_target_dependencies _target _out_var)
set(out_list)
+24 -28
View File
@@ -1,12 +1,13 @@
include(util)
INCLUDE(source_groups.cmake)
INCLUDE(voice_rec.cmake)
ADD_LIBRARY(code STATIC ${source_files} ${VOICE_REC_FILES})
target_compile_features(code PUBLIC cxx_std_11)
target_compile_features(code PUBLIC ${REQUIRED_CXX_FEATURES})
INCLUDE(default_files.cmake)
if (MSVC)
target_compile_definitions(code PUBLIC "PDB_DEBUGGING=1")
@@ -18,9 +19,7 @@ TARGET_INCLUDE_DIRECTORIES(code PUBLIC ${FREESPACE_HEADERS})
TARGET_INCLUDE_DIRECTORIES(code PUBLIC ${GENERATED_SOURCE_DIR})
TARGET_INCLUDE_DIRECTORIES(code PUBLIC ${GENERATED_SOURCE_DIR}/code)
if (FSO_BUILD_WITH_OPENGL)
target_link_libraries(code PUBLIC OpenGL)
endif()
target_link_libraries(code PUBLIC OpenGL)
TARGET_LINK_LIBRARIES(code PUBLIC openal)
TARGET_LINK_LIBRARIES(code PUBLIC ${LUA_LIBS})
@@ -46,13 +45,7 @@ target_link_libraries(code PUBLIC libRocket)
target_link_libraries(code PUBLIC pcp)
if (FSO_BUILD_WITH_VULKAN)
target_link_libraries(code PUBLIC vulkan-hpp)
endif()
target_link_libraries(code PUBLIC parsers)
target_link_libraries(code PUBLIC mdns)
target_link_libraries(code PUBLIC vulkan-hpp)
enable_clang_tidy(code)
@@ -63,8 +56,6 @@ ENDIF(FSO_USE_SPEECH)
TARGET_LINK_LIBRARIES(code PUBLIC jansson)
target_link_libraries(code PUBLIC variant)
# Headers for standalone "gui" on UNIX
IF(UNIX)
TARGET_LINK_LIBRARIES(code PUBLIC ${MONGOOSE_LIBS})
@@ -76,6 +67,22 @@ IF(FSO_BUILD_TOOLS)
ADD_SUBDIRECTORY(cfileextractor)
ENDIF(FSO_BUILD_TOOLS)
if (ENABLE_COTIRE)
set_target_properties(code PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h")
else()
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
target_compile_options(code PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
target_compile_options(code PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:/FI ${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
target_compile_options(code PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h>")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
target_compile_options(code PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-include${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h>")
ELSE()
MESSAGE("Unknown compiler for global includes. This will probably break the build.")
ENDIF()
endif()
if (FSO_RELEASE_LOGGING)
target_compile_definitions(code PUBLIC SCP_RELEASE_LOGGING)
endif()
@@ -83,20 +90,9 @@ endif()
if (FSO_BUILD_WITH_FFMPEG)
target_compile_definitions(code PUBLIC WITH_FFMPEG)
endif()
if (FSO_BUILD_WITH_OPENGL)
target_compile_definitions(code PUBLIC WITH_OPENGL)
endif()
if (FSO_BUILD_WITH_VULKAN)
target_compile_definitions(code PUBLIC WITH_VULKAN)
endif()
include(shaders.cmake)
target_embed_files(code FILES ${default_files_files} RELATIVE_TO "def_files")
handle_embedded_files(code)
set_precompiled_header(code "${CMAKE_CURRENT_SOURCE_DIR}/prefix_header.h")
include(util)
configure_cotire(code)
# Ensure that Xcode generates debug symbols on macOS for Debug builds
set_target_properties(code PROPERTIES XCODE_ATTRIBUTE_GCC_GENERATE_DEBUGGING_SYMBOLS[variant=Debug] "YES")
-8
View File
@@ -1,8 +0,0 @@
#include "Action.h"
namespace actions {
Action::~Action() = default;
}
-23
View File
@@ -1,23 +0,0 @@
#pragma once
#include "common.h"
namespace actions {
enum class ActionResult
{
Finished,
Errored,
Wait
};
class Action {
public:
virtual ~Action() = 0;
virtual ActionResult execute(ProgramLocals& locals) const = 0;
virtual std::unique_ptr<Action> clone() const = 0;
};
} // namespace actions
-20
View File
@@ -1,20 +0,0 @@
#include "ActionDefinition.h"
namespace actions {
ActionDefinition::ActionDefinition(SCP_string name, SCP_vector<ActionParameter> parameters)
: m_name(std::move(name)), m_parameters(std::move(parameters))
{
}
const SCP_string& ActionDefinition::getName() const
{
return m_name;
}
const SCP_vector<ActionParameter>& ActionDefinition::getParameters() const
{
return m_parameters;
}
} // namespace actions
-32
View File
@@ -1,32 +0,0 @@
#pragma once
#include "Action.h"
#include "actions/expression/ActionExpression.h"
#include "actions/expression/Value.h"
namespace actions {
struct ActionParameter {
SCP_string name;
expression::ValueType type;
};
class ActionDefinition {
public:
ActionDefinition(SCP_string name, SCP_vector<ActionParameter> parameters);
const SCP_string& getName() const;
const SCP_vector<actions::ActionParameter>& getParameters() const;
virtual flagset<ProgramContextFlags> getRequiredContext() const = 0;
virtual std::unique_ptr<Action> createAction(
const SCP_unordered_map<SCP_string, expression::ActionExpression>& parameterExpressions) const = 0;
private:
SCP_string m_name;
SCP_vector<ActionParameter> m_parameters;
};
} // namespace actions
-148
View File
@@ -1,148 +0,0 @@
#include "ActionDefinitionManager.h"
#include "BuiltinActionDefinition.h"
#include "actions/types/MoveToSubmodel.h"
#include "actions/types/ParticleEffectAction.h"
#include "actions/types/PlaySoundAction.h"
#include "actions/types/SetDirectionAction.h"
#include "actions/types/SetPositionAction.h"
#include "actions/types/WaitAction.h"
#include "utils/join_string.h"
namespace actions {
namespace {
void parseActionParameters(const SCP_vector<ActionParameter>& params,
SCP_unordered_map<SCP_string, expression::ActionExpression>& parameterExpressions,
const expression::ParseContext& context)
{
// We do not impose a set order of the parameters so we need to do something similar to the outer loop and
// check for every possibility in a loop.
for (size_t i = 0; i < params.size(); ++i) {
// We might be doing some empty loops here in case of errors but there is a bound so this will finish
// eventually
for (const auto& parameter : params) {
// Do not check for parameters which we already found
if (parameterExpressions.find(parameter.name) != parameterExpressions.end()) {
continue;
}
const auto paramString = "+" + parameter.name + ":";
if (!optional_string(paramString.c_str())) {
continue;
}
// We found our parameter!
parameterExpressions[parameter.name] =
expression::ActionExpression::parseFromTable(parameter.type, context);
break;
}
}
}
} // namespace
const ActionDefinitionManager& ActionDefinitionManager::instance()
{
static const ActionDefinitionManager manager = []() {
ActionDefinitionManager newManager;
newManager.addDefinition(
std::unique_ptr<ActionDefinition>(new BuiltinActionDefinition<types::MoveToSubmodel>("Move To Subobject")));
newManager.addDefinition(std::unique_ptr<ActionDefinition>(
new BuiltinActionDefinition<types::ParticleEffectAction>("Start Particle Effect")));
newManager.addDefinition(
std::unique_ptr<ActionDefinition>(new BuiltinActionDefinition<types::PlaySoundAction>("Play 3D Sound")));
newManager.addDefinition(
std::unique_ptr<ActionDefinition>(new BuiltinActionDefinition<types::SetDirectionAction>("Set Direction")));
newManager.addDefinition(
std::unique_ptr<ActionDefinition>(new BuiltinActionDefinition<types::SetPositionAction>("Set Position")));
newManager.addDefinition(
std::unique_ptr<ActionDefinition>(new BuiltinActionDefinition<types::WaitAction>("Wait")));
return newManager;
}();
return manager;
}
void ActionDefinitionManager::addDefinition(std::unique_ptr<ActionDefinition> def)
{
m_definitions.push_back(std::move(def));
}
std::unique_ptr<Action> ActionDefinitionManager::parseAction(const flagset<ProgramContextFlags>& context_flags,
const expression::ParseContext& context) const
{
// We search through all definitions for every time we want to check for an action. This is not the most efficient
// way to handle this since it results in an O(n^2) runtime. A better alternative would be to either construct a
// regex with all the accepted actions as alternatives (although runtime of this is also doubtful) or peek at the
// next token, extract the relevant part (The stuff between "+" and ":") and then look that up in a map. Then we
// would get down to O(n).
// Since this only happens at parse time, this is good enough for now.
for (const auto& actionDef : m_definitions) {
const auto parseString = "+" + actionDef->getName() + ":";
if (!optional_string(parseString.c_str())) {
continue;
}
SCP_unordered_map<SCP_string, expression::ActionExpression> parameterExpressions;
const auto& params = actionDef->getParameters();
if (params.size() == 1) {
// Single parameters are expected to be placed directly after the action name
parameterExpressions[params.front().name] =
expression::ActionExpression::parseFromTable(params.front().type, context);
} else {
parseActionParameters(params, parameterExpressions, context);
if (parameterExpressions.size() != params.size()) {
SCP_vector<ActionParameter> missingParameters;
std::copy_if(params.cbegin(),
params.cend(),
std::back_inserter(missingParameters),
[&parameterExpressions](const ActionParameter& param) {
const auto iter = parameterExpressions.find(param.name);
return iter == parameterExpressions.cend();
});
SCP_vector<SCP_string> missingParameterNames;
std::transform(missingParameters.cbegin(),
missingParameters.cend(),
std::back_inserter(missingParameterNames),
[](const ActionParameter& param) { return "+" + param.name; });
const auto namesList = util::join_container(missingParameterNames, ", ");
error_display(0, "Missing parameters for action '%s': %s", parseString.c_str(), namesList.c_str());
// Fix up the parameter list so that we can continue parsing
for (const auto& missingParam : missingParameters) {
parameterExpressions[missingParam.name] = expression::ActionExpression();
}
}
}
auto actionInstance = actionDef->createAction(parameterExpressions);
const auto requiredFlags = actionDef->getRequiredContext();
if ((context_flags & requiredFlags) != requiredFlags) {
// We are missing at least one context flag so this action is not valid here. We still return the action
// here though since that is the only way we can keep parsing the table without throwing random error
// messages at the user. However, this will trigger an Assertion (in debug) or crashes when the action is
// actually run later.
error_display(0,
"The action %s is not available in the current context. This will lead to an Assertion failure when "
"this action is triggered.",
parseString.c_str());
}
return actionInstance;
}
return std::unique_ptr<Action>();
}
} // namespace actions
-29
View File
@@ -1,29 +0,0 @@
#pragma once
#include "ActionDefinition.h"
namespace actions {
class ActionDefinitionManager {
public:
// This type is supposed to be global so it may not be copied
ActionDefinitionManager(const ActionDefinitionManager&) = delete;
ActionDefinitionManager& operator=(const ActionDefinitionManager&) = delete;
ActionDefinitionManager(ActionDefinitionManager&&) noexcept = default;
ActionDefinitionManager& operator=(ActionDefinitionManager&&) noexcept = default;
std::unique_ptr<Action> parseAction(const flagset<ProgramContextFlags>& context_flags,
const expression::ParseContext& context) const;
static const ActionDefinitionManager& instance();
private:
ActionDefinitionManager() = default;
void addDefinition(std::unique_ptr<ActionDefinition> def);
SCP_vector<std::unique_ptr<ActionDefinition>> m_definitions;
};
} // namespace actions
-2
View File
@@ -1,2 +0,0 @@
#include "BuiltinActionDefinition.h"
-36
View File
@@ -1,36 +0,0 @@
#pragma once
#include "ActionDefinition.h"
#include "expression/Value.h"
namespace actions {
template <typename TAction>
class BuiltinActionDefinition : public ActionDefinition {
using ActionValueType = typename TAction::ValueType;
public:
BuiltinActionDefinition(SCP_string name)
: ActionDefinition(std::move(name), {{"parameter", expression::ValueTypeTraits<ActionValueType>::type}})
{
}
flagset<ProgramContextFlags> getRequiredContext() const override
{
return flagset<ProgramContextFlags>(TAction::getRequiredExecutionContextFlags());
}
std::unique_ptr<Action> createAction(
const SCP_unordered_map<SCP_string, expression::ActionExpression>& parameterExpressions) const override
{
const auto paramIter = parameterExpressions.find("parameter");
// This should have been caught earlier
Assertion(paramIter != parameterExpressions.cend(), "Could not find built-in parameter!");
return std::unique_ptr<Action>(new TAction(paramIter->second.template asTyped<ActionValueType>()));
}
};
} // namespace actions
-174
View File
@@ -1,174 +0,0 @@
#include "Program.h"
#include "Action.h"
#include "actions/ActionDefinitionManager.h"
#include "executor/global_executors.h"
#include "tracing/Monitor.h"
#include "tracing/categories.h"
#include "tracing/tracing.h"
namespace {
using namespace actions;
tracing::Monitor<int> RunningProgramsMonitor("RunningPrograms", 0);
struct ProgramRunner {
tracing::RunningCounter runningCounter{RunningProgramsMonitor};
ProgramInstance instance;
explicit ProgramRunner(const ProgramInstance& _instance) : instance(_instance) {}
executor::Executor::CallbackResult operator()()
{
TRACE_SCOPE(tracing::ProgramStepOne);
auto res = instance.step();
switch (res) {
case ProgramState::Running:
// If the program is still running then we need to reschedule our execution
return executor::Executor::CallbackResult::Reschedule;
case ProgramState::Done:
case ProgramState::Errored:
default:
return executor::Executor::CallbackResult::Done;
}
}
};
} // namespace
namespace actions {
ProgramInstance::ProgramInstance(const actions::Program* program) : _program(program) {}
ProgramState ProgramInstance::step()
{
if (!_locals.host.IsValid()) {
return ProgramState::Done;
}
auto& actions = _program->getActions();
for (; _currentInstruction < actions.size(); ++_currentInstruction) {
auto& action = actions[_currentInstruction];
auto result = action->execute(_locals);
if (result == ActionResult::Errored) {
return ProgramState::Errored;
}
if (result == ActionResult::Wait) {
// Action is not done yet, call again next frame
return ProgramState::Running;
}
// Action finished, run next action in program
}
// End of program reached, we are done now
return ProgramState::Done;
}
ProgramLocals& ProgramInstance::locals()
{
return _locals;
}
const ProgramLocals& ProgramInstance::locals() const
{
return _locals;
}
const SCP_vector<std::unique_ptr<actions::Action>>& Program::getActions() const
{
return _actions;
}
Program::Program() = default;
ProgramInstance Program::newInstance() const
{
return ProgramInstance(this);
}
void Program::parseActions(const flagset<ProgramContextFlags>& context_flags, const expression::ParseContext& context)
{
while (true) {
auto action = ActionDefinitionManager::instance().parseAction(context_flags, context);
if (!action) {
break;
}
_actions.push_back(std::move(action));
}
}
Program::Program(const Program& other) { *this = other; }
Program& Program::operator=(const Program& other)
{
_actions.clear();
_actions.reserve(other._actions.size());
for (auto& action : other._actions) {
_actions.emplace_back(action->clone());
}
return *this;
}
Program& Program::operator=(Program&&) noexcept = default;
Program::Program(Program&&) noexcept = default;
const SCP_vector<actions::Program>& ProgramSet::getPrograms() const
{
return _programs;
}
ProgramSet::ProgramSet() = default;
ProgramSet::ProgramSet(const flagset<ProgramContextFlags>& context_flags) : _contextFlags(context_flags) {}
void ProgramSet::start(object* objp, const vec3d* local_pos, const matrix* local_orient, int submodel) const
{
if (_contextFlags[ProgramContextFlags::HasObject]) {
Assertion(objp != nullptr, "Invalid object pointer supplied.");
}
if (_contextFlags[ProgramContextFlags::HasSubobject]) {
Assertion(submodel >= 0, "Invalid subobject supplied.");
}
for (const auto& prog : _programs) {
auto instance = prog.newInstance();
instance.locals().host = object_h(objp);
instance.locals().localPosition = *local_pos;
instance.locals().localOrient = *local_orient;
instance.locals().hostSubobject = submodel;
instance.locals().variables = getDefaultTableVariables();
// Just use the executor system to take care of running this program
executor::OnSimulationExecutor->post(ProgramRunner(instance));
}
}
ProgramSet ProgramSet::parseProgramSet(const char* tag, const flagset<ProgramContextFlags>& context_flags)
{
ProgramSet set(context_flags);
const auto parseContext = getTableParseContext();
while (optional_string(tag)) {
Program p;
p.parseActions(context_flags, parseContext);
set._programs.push_back(std::move(p));
}
return set;
}
} // namespace actions
-112
View File
@@ -1,112 +0,0 @@
#pragma once
#include "globalincs/pstypes.h"
#include "Action.h"
#include "common.h"
namespace actions {
class Program;
class ProgramSet;
enum class ProgramState
{
Running,
Done,
Errored
};
/**
* @brief An instance of a program execution
*
* A program instance contains all information related to a single execution of a program. A program instance is
* independent from other instances. Local variables used by actions are stored in a specific structure which can be
* used by actions to keep track of state in this specific instance.
*/
class ProgramInstance {
size_t _currentInstruction = 0;
ProgramLocals _locals;
const Program* _program = nullptr;
public:
explicit ProgramInstance(const Program* program);
ProgramState step();
ProgramLocals& locals();
const ProgramLocals& locals() const;
};
/**
* @brief A program specified in a table
*
* A program is a sequential collection of Actions which are executed in sequence.
*/
class Program {
SCP_vector<std::unique_ptr<Action>> _actions;
public:
Program();
Program(const Program& other);
Program& operator=(const Program& other);
Program(Program&& other) noexcept;
Program& operator=(Program&& other) noexcept;
const SCP_vector<std::unique_ptr<actions::Action>>& getActions() const;
/**
* @brief Creates a new program instance from this program
*
* The program instance is initialized to its initial values.
*
* @return The new program instance
*/
ProgramInstance newInstance() const;
void parseActions(const flagset<ProgramContextFlags>& context_flags, const expression::ParseContext& context);
};
/**
* @brief A set of parsed programs
*
* Programs are parsed in sets of zero or more programs to make it possible for the content creator to split up
* programs.
*/
class ProgramSet {
flagset<ProgramContextFlags> _contextFlags;
SCP_vector<Program> _programs;
public:
ProgramSet();
explicit ProgramSet(const flagset<ProgramContextFlags>& context_flags);
const SCP_vector<actions::Program>& getPrograms() const;
/**
* @brief Starts the execution of all programs within this set with the specified parameters
* @param objp The object on which this program is executed
* @param local_pos The local position relative to the object or the subsystem if specified
* @param local_orien The local orientation relative to the object or the subsystem if specified
* @param submodel The submodel of the model to which this program is attached to.
*/
void start(object* objp, const vec3d* local_pos, const matrix* local_orient, int submodel = -1) const;
/**
* @brief Parses a program set of zero or more programs
*
* The tag is entirely optional and if it doesn't appear in the current table then an empty set will be returned
* which does nothing if started.
*
* @param tag The tag which is required before a program can be specified
* @param context_flags A set of flags which specify in which environment the program will be used. This is used
* mainly for validating the used actions.
* @return The parsed program set.
*/
static ProgramSet parseProgramSet(const char* tag, const flagset<ProgramContextFlags>& context_flags = {});
};
} // namespace actions
-27
View File
@@ -1,27 +0,0 @@
#include "common.h"
namespace actions {
expression::ParseContext getTableParseContext()
{
expression::ParseContext ctx;
auto& locals = ctx.variables.addScope("locals");
locals.addMember("position", expression::ValueType::Vector);
locals.addMember("direction", expression::ValueType::Vector);
return ctx;
}
expression::ProgramVariables getDefaultTableVariables()
{
expression::ProgramVariables vars;
vars.setValue({"locals", "position"}, expression::Value(vmd_zero_vector));
vars.setValue({"locals", "direction"}, expression::Value(vmd_zero_vector));
return vars;
}
} // namespace actions
-59
View File
@@ -1,59 +0,0 @@
#pragma once
#include "globalincs/flagset.h"
#include "actions/expression/ParseContext.h"
#include "actions/expression/ProgramVariables.h"
#include "math/vecmat.h"
#include "object/object.h"
class object;
class ship_subsys;
namespace actions {
struct ProgramLocals {
object_h host;
vec3d localPosition = vmd_zero_vector;
matrix localOrient = vmd_identity_matrix;
int hostSubobject = -1;
int waitTimestamp = 0;
expression::ProgramVariables variables;
};
/**
* @brief A list of flags for altering the program parsing behavior
*
* This should be used for differentiating between different program environments when validating the program (e.g. a
* particle effect requires an object host).
*/
// clang-format off
FLAG_LIST(ProgramContextFlags) {
HasObject = 0, //!< The program will be started with an object host
HasSubobject, //!< The program will be started with a subobject host
NUM_VALUES
};
// clang-format on
/**
* @brief Constructs the "table" parse context
*
* This is the context that is available when parsing a program from an external table (e.g. ships or weapons).
*
* @return The parse context
*/
expression::ParseContext getTableParseContext();
/**
* @brief Gets a program variables instance initialized with the default values
*
* The values are consistent with what is required for the default table parse context;
*
* @return The program variables
*/
expression::ProgramVariables getDefaultTableVariables();
} // namespace actions
@@ -1,66 +0,0 @@
#include "ActionExpression.h"
#include "ExpressionParser.h"
#include "TypeDefinition.h"
#include "actions/expression/nodes/AbstractExpression.h"
namespace actions {
namespace expression {
namespace {
SCP_string getTypeName(ValueType type)
{
const auto& typeDef = TypeDefinition::forValueType(type);
return typeDef.getName();
}
} // namespace
ActionExpression ActionExpression::parseFromTable(ValueType expectedReturnType, const ParseContext& context)
{
SCP_string expressionText;
stuff_string(expressionText, F_NAME);
ExpressionParser parser(expressionText);
auto expression = parser.parse(context);
if (!expression) {
error_display(0, "Failed to parse action expression:\n%s", parser.getErrorText().c_str());
return ActionExpression();
}
auto type = expression->getExpressionType();
// Check if the type this evaluates to matches what we expect
if (!checkTypeWithImplicitConversion(type, expectedReturnType)) {
error_display(0,
"Expression evaluates to type <%s> but <%s> was expected!",
getTypeName(type).c_str(),
getTypeName(expectedReturnType).c_str());
return ActionExpression();
}
// Everything is valid
return ActionExpression(expression);
}
Value ActionExpression::execute(const ProgramVariables& variables) const
{
// Do not crash on invalid expressions
if (!isValid()) {
return Value();
}
return m_expression->execute(variables);
}
bool ActionExpression::isValid() const
{
return m_expression != nullptr;
}
} // namespace expression
} // namespace actions
@@ -1,70 +0,0 @@
#pragma once
#include "ParseContext.h"
#include "ProgramVariables.h"
#include "TypeDefinition.h"
#include "parse/parselo.h"
namespace actions {
namespace expression {
namespace nodes {
class AbstractExpression;
}
template <typename T>
class TypedActionExpression;
class ActionExpression {
public:
ActionExpression() = default;
Value execute(const ProgramVariables& variables) const;
bool isValid() const;
template <typename T>
TypedActionExpression<T> asTyped() const;
static ActionExpression parseFromTable(ValueType expectedReturnType, const ParseContext& context);
protected:
explicit ActionExpression(std::shared_ptr<nodes::AbstractExpression> expression)
: m_expression(std::move(expression))
{
}
std::shared_ptr<nodes::AbstractExpression> m_expression;
};
template <typename T>
class TypedActionExpression {
public:
explicit TypedActionExpression(ActionExpression expression) : m_expression(std::move(expression)) {}
T execute(const ProgramVariables& variables) const
{
// Do not crash on invalid expressions
if (!m_expression.isValid()) {
return T();
}
return m_expression.execute(variables).template get<T>();
}
static TypedActionExpression<T> parseFromTable(const ParseContext& context)
{
return ActionExpression::parseFromTable(ValueTypeTraits<T>::type, context).template asTyped<T>();
}
private:
ActionExpression m_expression;
};
template <typename T>
TypedActionExpression<T> ActionExpression::asTyped() const
{
return TypedActionExpression<T>(*this);
}
} // namespace expression
} // namespace actions
@@ -1,194 +0,0 @@
#include "ExpressionParser.h"
#include "actions/expression/nodes/FunctionCallExpression.h"
#include "actions/expression/nodes/LiteralExpression.h"
#include "actions/expression/nodes/RandomRangeExpression.h"
#include "actions/expression/nodes/VariableReferenceExpression.h"
#include "actions/expression/nodes/VectorConstructorExpression.h"
#include "libs/antlr/ErrorListener.h"
PUSH_SUPPRESS_WARNINGS
#include "action_expression/generated/ActionExpressionLexer.h"
#include "action_expression/generated/ActionExpressionParser.h"
#include "action_expression/generated/ActionExpressionVisitor.h"
POP_SUPPRESS_WARNINGS
namespace actions {
namespace expression {
namespace {
class ExpressionBuilderVisitor : public ActionExpressionVisitor {
public:
antlrcpp::Any visitExpression_main(ActionExpressionParser::Expression_mainContext* context) override
{
return visit(context->expression());
}
antlrcpp::Any visitExpression(ActionExpressionParser::ExpressionContext* context) override
{
if (context->value_expression() != nullptr) {
return visit(context->value_expression());
}
if (context->parenthesis_expression()) {
return visit(context->parenthesis_expression());
}
if (context->random_range_expression()) {
return visit(context->random_range_expression());
}
if (context->variable_reference_expression()) {
return visit(context->variable_reference_expression());
}
// This is an operator so treat it as one.
antlr4::Token* operatorTok;
SCP_string operatorText;
if (context->PLUS() != nullptr) {
operatorTok = context->PLUS()->getSymbol();
operatorText = context->PLUS()->getText();
} else {
operatorTok = context->MINUS()->getSymbol();
operatorText = context->MINUS()->getText();
}
const auto leftExpr = visit(context->expression(0)).as<std::shared_ptr<nodes::AbstractExpression>>();
const auto rightExpr = visit(context->expression(1)).as<std::shared_ptr<nodes::AbstractExpression>>();
auto operatorExpression = std::make_shared<nodes::FunctionCallExpression>(operatorTok,
true,
std::move(operatorText),
SCP_vector<std::shared_ptr<nodes::AbstractExpression>>{leftExpr, rightExpr});
return std::static_pointer_cast<nodes::AbstractExpression>(operatorExpression);
}
antlrcpp::Any visitVariable_reference_expression(
ActionExpressionParser::Variable_reference_expressionContext* context) override
{
const auto identifiers = context->IDENTIFIER();
SCP_vector<SCP_string> partNames;
partNames.reserve(identifiers.size());
std::transform(identifiers.begin(),
identifiers.end(),
std::back_inserter(partNames),
[](antlr4::tree::TerminalNode* node) { return node->getText(); });
SCP_vector<antlr4::Token*> partTokens;
partTokens.reserve(identifiers.size());
std::transform(identifiers.begin(),
identifiers.end(),
std::back_inserter(partTokens),
[](antlr4::tree::TerminalNode* node) { return node->getSymbol(); });
auto expression =
std::make_shared<nodes::VariableReferenceExpression>(std::move(partNames), std::move(partTokens));
return std::static_pointer_cast<nodes::AbstractExpression>(expression);
}
antlrcpp::Any visitRandom_range_expression(ActionExpressionParser::Random_range_expressionContext* context) override
{
auto expression = std::make_shared<nodes::RandomRangeExpression>(context->RAND_L_PAREN()->getSymbol(),
visit(context->expression(0)).as<std::shared_ptr<nodes::AbstractExpression>>(),
visit(context->expression(1)).as<std::shared_ptr<nodes::AbstractExpression>>());
return std::static_pointer_cast<nodes::AbstractExpression>(expression);
}
antlrcpp::Any visitLiteral_expression(ActionExpressionParser::Literal_expressionContext* context) override
{
std::shared_ptr<nodes::LiteralExpression> expression;
if (context->FLOAT() != nullptr) {
expression = std::make_shared<nodes::LiteralExpression>(context->FLOAT()->getSymbol(),
Value(std::stof(context->FLOAT()->getText())));
} else if (context->INT() != nullptr) {
expression = std::make_shared<nodes::LiteralExpression>(context->INT()->getSymbol(),
Value(std::stoi(context->INT()->getText())));
} else {
const auto idText = context->STRING()->getText();
// Cut off the first and last characters since those are the < > braces
expression = std::make_shared<nodes::LiteralExpression>(context->STRING()->getSymbol(),
Value(idText.substr(1, idText.size() - 2)));
}
return std::static_pointer_cast<nodes::AbstractExpression>(expression);
}
antlrcpp::Any visitParenthesis_expression(ActionExpressionParser::Parenthesis_expressionContext* context) override
{
return visit(context->expression());
}
antlrcpp::Any visitValue_expression(ActionExpressionParser::Value_expressionContext* context) override
{
return visitChildren(context);
}
antlrcpp::Any visitVec3d_constructor(ActionExpressionParser::Vec3d_constructorContext* context) override
{
auto xExpression = visit(context->expression(0)).as<std::shared_ptr<nodes::AbstractExpression>>();
auto yExpression = visit(context->expression(1)).as<std::shared_ptr<nodes::AbstractExpression>>();
auto zExpression = visit(context->expression(2)).as<std::shared_ptr<nodes::AbstractExpression>>();
auto expression = std::make_shared<nodes::VectorConstructorExpression>(context->L_PAREN()->getSymbol(),
xExpression,
yExpression,
zExpression);
return std::static_pointer_cast<nodes::AbstractExpression>(expression);
}
};
} // namespace
ExpressionParser::ExpressionParser(SCP_string expressionText) : m_expressionText(std::move(expressionText)) {}
std::shared_ptr<nodes::AbstractExpression> ExpressionParser::parse(const ParseContext& context)
{
antlr4::ANTLRInputStream input(m_expressionText);
ActionExpressionLexer lexer(&input);
antlr4::CommonTokenStream tokens(&lexer);
::ActionExpressionParser parser(&tokens);
// By default we log to stderr which we do not want
parser.removeErrorListeners();
libs::antlr::ErrorListener errListener;
parser.addErrorListener(&errListener);
antlr4::tree::ParseTree* tree = parser.expression_main();
std::shared_ptr<nodes::AbstractExpression> exprReturn;
if (errListener.diagnostics.empty()) {
// Only do semantic checking if syntax is valid
ExpressionBuilderVisitor builder;
exprReturn = tree->accept(&builder).as<std::shared_ptr<nodes::AbstractExpression>>();
if (!exprReturn->validate(&parser, context)) {
exprReturn = nullptr;
} else {
exprReturn->validationDone();
}
}
if (!errListener.diagnostics.empty()) {
SCP_stringstream outStream;
for (const auto& diag : errListener.diagnostics) {
SCP_string tokenUnderline;
if (diag.tokenLength > 1) {
tokenUnderline = SCP_string(diag.tokenLength - 1, '~');
}
outStream << m_expressionText << "\n"
<< SCP_string(diag.columnInLine, ' ') << "^" << tokenUnderline << "\n"
<< diag.errorMessage << "\n";
}
m_errorText = outStream.str();
return nullptr;
}
return exprReturn;
}
const SCP_string& ExpressionParser::getErrorText() const
{
return m_errorText;
}
} // namespace expression
} // namespace actions
@@ -1,27 +0,0 @@
#pragma once
#include "globalincs/pstypes.h"
#include "ParseContext.h"
#include "actions/expression/nodes/AbstractExpression.h"
namespace actions {
namespace expression {
class ExpressionParser {
public:
ExpressionParser(SCP_string expressionText);
std::shared_ptr<nodes::AbstractExpression> parse(const ParseContext& context);
const SCP_string& getErrorText() const;
private:
SCP_string m_expressionText;
SCP_string m_errorText;
};
} // namespace expression
} // namespace actions
@@ -1,93 +0,0 @@
#include "FunctionManager.h"
#include "TypeDefinition.h"
#include "math/vecmat.h"
namespace actions {
namespace expression {
namespace {
template <typename T>
Value value_plus(const SCP_vector<Value>& parameters)
{
return Value(parameters[0].get<T>() + parameters[1].get<T>());
}
template <typename T>
Value value_minus(const SCP_vector<Value>& parameters)
{
return Value(parameters[0].get<T>() - parameters[1].get<T>());
}
} // namespace
const FunctionManager& FunctionManager::instance()
{
static const FunctionManager manager = []() {
FunctionManager newManager;
newManager.addOperator("+", {ValueType::Integer, ValueType::Integer}, ValueType::Integer, value_plus<int>);
newManager.addOperator("+", {ValueType::Float, ValueType::Float}, ValueType::Float, value_plus<float>);
newManager.addOperator("+", {ValueType::Vector, ValueType::Vector}, ValueType::Vector, value_plus<vec3d>);
newManager.addOperator("-", {ValueType::Integer, ValueType::Integer}, ValueType::Integer, value_minus<int>);
newManager.addOperator("-", {ValueType::Float, ValueType::Float}, ValueType::Float, value_minus<float>);
newManager.addOperator("-", {ValueType::Vector, ValueType::Vector}, ValueType::Vector, value_minus<vec3d>);
return newManager;
}();
return manager;
}
void FunctionManager::addOperator(const SCP_string& name,
std::initializer_list<ValueType> parameterTypes,
ValueType returnType,
FunctionImplementation implementation)
{
m_operators[name].push_back({name, parameterTypes, returnType, std::move(implementation)});
}
const FunctionDefinition* FunctionManager::findOperator(const SCP_string& name,
const SCP_vector<ValueType>& parameters) const
{
const auto iter = m_operators.find(name);
if (iter == m_operators.end()) {
return nullptr;
}
// Prefer exact matches
for (const auto& funcDef : iter->second) {
if (funcDef.parameterTypes == parameters) {
return &funcDef;
}
}
// Now check if there are matches with implicit conversions
for (const auto& funcDef : iter->second) {
// Reject functions with different amount of elements
if (funcDef.parameterTypes.size() != parameters.size()) {
continue;
}
auto funcParamIter = funcDef.parameterTypes.cbegin();
auto actualParamIter = parameters.cbegin();
bool match = true;
for (; funcParamIter != funcDef.parameterTypes.cend(); ++funcParamIter, ++actualParamIter) {
if (!checkTypeWithImplicitConversion(*actualParamIter, *funcParamIter)) {
// Also doesn't match with implicit conversions
match = false;
break;
}
}
if (match) {
return &funcDef;
}
}
return nullptr;
}
FunctionManager::FunctionManager() = default;
} // namespace expression
} // namespace actions
-45
View File
@@ -1,45 +0,0 @@
#pragma once
#include "Value.h"
namespace actions {
namespace expression {
using FunctionImplementation = std::function<Value(const SCP_vector<Value>& parameters)>;
struct FunctionDefinition {
SCP_string name;
SCP_vector<ValueType> parameterTypes;
ValueType returnType;
FunctionImplementation implementation;
};
class FunctionManager {
public:
// This type is supposed to be global so it may not be copied
FunctionManager(const FunctionManager&) = delete;
FunctionManager& operator=(const FunctionManager&) = delete;
FunctionManager(FunctionManager&&) noexcept = default;
FunctionManager& operator=(FunctionManager&&) noexcept = default;
void addOperator(const SCP_string& name,
std::initializer_list<ValueType> parameterTypes,
ValueType returnType,
FunctionImplementation implementation);
const FunctionDefinition* findOperator(const SCP_string& name, const SCP_vector<ValueType>& parameterTypes) const;
static const FunctionManager& instance();
private:
FunctionManager();
SCP_unordered_map<SCP_string, SCP_vector<FunctionDefinition>> m_operators;
};
} // namespace expression
} // namespace actions
-13
View File
@@ -1,13 +0,0 @@
#pragma once
#include "ProgramVariables.h"
namespace actions {
namespace expression {
struct ParseContext {
ProgramVariablesDefinition variables;
};
} // namespace expression
} // namespace actions
@@ -1,61 +0,0 @@
#include "ProgramVariables.h"
namespace actions {
namespace expression {
ProgramVariablesDefinition& ProgramVariablesDefinition::addScope(const SCP_string& name)
{
auto scope = std::unique_ptr<ProgramVariablesDefinition>(new ProgramVariablesDefinition());
auto scopePtr = scope.get();
m_scopes.insert(std::make_pair(name, std::move(scope)));
return *scopePtr;
}
void ProgramVariablesDefinition::addMember(const SCP_string& name, ValueType type)
{
m_memberTypes[name] = type;
}
ProgramVariablesDefinition* ProgramVariablesDefinition::getScope(const SCP_string& name) const
{
const auto iter = m_scopes.find(name);
if (iter == m_scopes.cend()) {
return nullptr;
}
return iter->second.get();
}
ValueType ProgramVariablesDefinition::getMemberType(const SCP_string& name) const
{
const auto iter = m_memberTypes.find(name);
if (iter == m_memberTypes.cend()) {
return ValueType::Invalid;
}
return iter->second;
}
Value ProgramVariables::getValue(std::initializer_list<const char*> memberPathParts) const
{
return getValue<decltype(memberPathParts)>(memberPathParts);
}
void ProgramVariables::setValue(std::initializer_list<const char*> memberPathParts, Value value)
{
setValue<decltype(memberPathParts)>(memberPathParts, std::move(value));
}
Value ProgramVariables::getValue(const SCP_string& fullMemberName) const
{
const auto iter = m_values.find(fullMemberName);
// This should have been validated earlier
Assertion(iter != m_values.end(), "Could not find member %s in variables!", fullMemberName.c_str());
return iter->second;
}
} // namespace expression
} // namespace actions
@@ -1,61 +0,0 @@
#pragma once
#include "Value.h"
#include "utils/join_string.h"
namespace actions {
namespace expression {
struct ProgramVariables {
public:
template <typename TContainer>
static SCP_string getMemberName(const TContainer& memberPathParts)
{
return util::join_container(memberPathParts, ".");
}
template <typename TContainer>
Value getValue(const TContainer& memberPathParts) const
{
const auto name = getMemberName(memberPathParts);
return getValue(name);
}
Value getValue(std::initializer_list<const char*> memberPathParts) const;
Value getValue(const SCP_string& fullMemberName) const;
template <typename TContainer>
void setValue(const TContainer& memberPathParts, Value value)
{
const auto name = getMemberName(memberPathParts);
m_values[name] = std::move(value);
}
void setValue(std::initializer_list<const char*> memberPathParts, Value value);
private:
SCP_unordered_map<SCP_string, Value> m_values;
};
class ProgramVariablesDefinition {
public:
ProgramVariablesDefinition& addScope(const SCP_string& name);
void addMember(const SCP_string& name, ValueType type);
ProgramVariablesDefinition* getScope(const SCP_string& name) const;
ValueType getMemberType(const SCP_string& name) const;
private:
SCP_unordered_map<SCP_string, std::unique_ptr<ProgramVariablesDefinition>> m_scopes;
SCP_unordered_map<SCP_string, ValueType> m_memberTypes;
};
} // namespace expression
} // namespace actions
@@ -1,60 +0,0 @@
#include "TypeDefinition.h"
namespace actions {
namespace expression {
// Integers can be safely converted to floats (for the most part)
TypeDefinition TypeDefinition::s_integer("Integer", {ValueType::Float});
// No implicit conversions here
TypeDefinition TypeDefinition::s_float("Float", {});
TypeDefinition TypeDefinition::s_vector("Vector", {});
// Identifiers are a technicality needed for making non-math values work but they have no further use other than their
// string content
TypeDefinition TypeDefinition::s_identifier("Identifier", {});
TypeDefinition::TypeDefinition(SCP_string name, SCP_vector<actions::expression::ValueType> allowedImplicitConversion)
: m_name(std::move(name)), m_allowedImplicitConversions(std::move(allowedImplicitConversion))
{
}
const SCP_string& TypeDefinition::getName() const
{
return m_name;
}
const SCP_vector<actions::expression::ValueType>& TypeDefinition::getAllowedImplicitConversions() const
{
return m_allowedImplicitConversions;
}
const TypeDefinition& TypeDefinition::forValueType(ValueType type)
{
switch (type) {
case ValueType::Integer:
return s_integer;
case ValueType::Float:
return s_float;
case ValueType::Vector:
return s_vector;
case ValueType::String:
return s_identifier;
default:
UNREACHABLE("Invalid value type!");
return s_integer; // Make compiler happy
}
}
bool checkTypeWithImplicitConversion(ValueType currentType, ValueType expectedType)
{
if (currentType == expectedType) {
// No need to consider implicit conversions;
return true;
}
const auto& currentTypeDef = TypeDefinition::forValueType(currentType);
const auto& allowedConversions = currentTypeDef.getAllowedImplicitConversions();
// For now, no transitiv conversions are allowed
return std::find(allowedConversions.cbegin(), allowedConversions.cend(), expectedType) != allowedConversions.cend();
}
} // namespace expression
} // namespace actions
-40
View File
@@ -1,40 +0,0 @@
#pragma once
#include "Value.h"
namespace actions {
namespace expression {
class TypeDefinition {
public:
TypeDefinition(SCP_string name, SCP_vector<actions::expression::ValueType> allowedImplicitConversion);
const SCP_string& getName() const;
const SCP_vector<actions::expression::ValueType>& getAllowedImplicitConversions() const;
static const TypeDefinition& forValueType(ValueType type);
// This type is supposed to be global so it may not be copied
TypeDefinition(const TypeDefinition&) = delete;
TypeDefinition& operator=(const TypeDefinition&) = delete;
TypeDefinition(TypeDefinition&&) = delete;
TypeDefinition& operator=(TypeDefinition&&) = delete;
private:
SCP_string m_name;
// The types this type is allowed to implicitly convert to
SCP_vector<ValueType> m_allowedImplicitConversions;
static TypeDefinition s_integer;
static TypeDefinition s_float;
static TypeDefinition s_vector;
static TypeDefinition s_identifier;
};
bool checkTypeWithImplicitConversion(ValueType currentType, ValueType expectedType);
} // namespace expression
} // namespace actions
-80
View File
@@ -1,80 +0,0 @@
#include "Value.h"
#include "math/vecmat.h"
namespace actions {
namespace expression {
Value::Value(int val) : m_value(val) {}
Value::Value(float val) : m_value(val) {}
Value::Value(const vec3d& val) : m_value(val) {}
Value::Value(SCP_string val) : m_value(std::move(val)) {}
ValueType actions::expression::Value::getType() const
{
switch (m_value.index()) {
case 1:
return ValueType::Integer;
case 2:
return ValueType::Float;
case 3:
return ValueType::Vector;
case 4:
return ValueType::String;
default:
return ValueType::Invalid;
}
}
int Value::getInteger() const
{
return get<int>();
}
float Value::getFloat() const
{
return get<float>();
}
vec3d Value::getVector() const
{
return get<vec3d>();
}
SCP_string Value::getIdentifier() const
{
return get<SCP_string>();
}
bool operator==(const Value& lhs, const Value& rhs)
{
return lhs.m_value == rhs.m_value;
}
bool operator!=(const Value& lhs, const Value& rhs)
{
return !(rhs == lhs);
}
std::ostream& operator<<(std::ostream& os, const Value& value)
{
os << "Value<";
switch (value.getType()) {
case ValueType::Invalid:
os << "INVALID";
break;
case ValueType::Integer:
os << value.get<int>();
break;
case ValueType::Float:
os << value.get<float>();
break;
case ValueType::Vector:
os << value.get<vec3d>();
break;
case ValueType::String:
os << value.get<SCP_string>();
break;
}
os << ">";
return os;
}
} // namespace expression
} // namespace actions
-104
View File
@@ -1,104 +0,0 @@
#pragma once
#include "globalincs/pstypes.h"
#include <mpark/variant.hpp>
namespace actions {
namespace expression {
namespace detail {
template <typename ToType>
struct implicit_conversion {
template <typename T>
ToType operator()(const T&)
{
throw std::runtime_error("Invalid implicit conversion.");
}
};
template<>
struct implicit_conversion<float> {
inline float operator()(int val) {
return i2fl(val);
}
template <typename T>
float operator()(const T&)
{
throw std::runtime_error("Invalid implicit conversion.");
}
};
} // namespace detail
enum class ValueType
{
Invalid,
Integer,
Float,
Vector,
String,
};
template <typename T>
struct ValueTypeTraits;
template <>
struct ValueTypeTraits<int> {
static constexpr ValueType type = ValueType::Integer;
};
template <>
struct ValueTypeTraits<float> {
static constexpr ValueType type = ValueType::Float;
};
template <>
struct ValueTypeTraits<vec3d> {
static constexpr ValueType type = ValueType::Vector;
};
template <>
struct ValueTypeTraits<SCP_string> {
static constexpr ValueType type = ValueType::String;
};
class Value {
public:
Value() = default;
explicit Value(int val);
explicit Value(float val);
explicit Value(const vec3d& val);
explicit Value(SCP_string val);
ValueType getType() const;
int getInteger() const;
float getFloat() const;
vec3d getVector() const;
SCP_string getIdentifier() const;
template <typename T>
T get() const
{
const auto currentType = getType();
const auto expectedType = ValueTypeTraits<T>::type;
if (currentType == expectedType) {
// No conversion necessary
return mpark::get<T>(m_value);
}
return mpark::visit(detail::implicit_conversion<T>{}, m_value);
}
friend bool operator==(const Value& lhs, const Value& rhs);
friend bool operator!=(const Value& lhs, const Value& rhs);
friend std::ostream& operator<<(std::ostream& os, const Value& value);
private:
mpark::variant<mpark::monostate, int, float, vec3d, SCP_string> m_value;
};
} // namespace expression
} // namespace actions
@@ -1,31 +0,0 @@
#include "AbstractExpression.h"
namespace actions {
namespace expression {
namespace nodes {
AbstractExpression::AbstractExpression(antlr4::Token* token) : m_token(token) {}
AbstractExpression::~AbstractExpression() = default;
antlr4::Token* AbstractExpression::getToken() const
{
return m_token;
}
ValueType AbstractExpression::getExpressionType() const
{
// Since expressions are immutable, caching this will be more efficient
if (m_cachedType == ValueType::Invalid) {
m_cachedType = determineReturnType();
}
return m_cachedType;
}
void AbstractExpression::validationDone()
{
// This pointer will become invalid after this so reset it now to avoid issues
m_token = nullptr;
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,38 +0,0 @@
#pragma once
#include "actions/expression/ParseContext.h"
#include "actions/expression/Value.h"
#include <Parser.h>
#include <Token.h>
namespace actions {
namespace expression {
namespace nodes {
class AbstractExpression {
public:
AbstractExpression(antlr4::Token* token);
virtual ~AbstractExpression();
virtual Value execute(const ProgramVariables& variables) const = 0;
virtual bool validate(antlr4::Parser* parser, const ParseContext& context) = 0;
virtual void validationDone();
ValueType getExpressionType() const;
antlr4::Token* getToken() const;
protected:
virtual ValueType determineReturnType() const = 0;
antlr4::Token* m_token = nullptr;
mutable ValueType m_cachedType = ValueType::Invalid;
};
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,95 +0,0 @@
#include "FunctionCallExpression.h"
#include "actions/expression/TypeDefinition.h"
namespace actions {
namespace expression {
namespace nodes {
FunctionCallExpression::FunctionCallExpression(antlr4::Token* token,
bool isOperator,
SCP_string functionName,
SCP_vector<std::shared_ptr<AbstractExpression>> parameterExpressions)
: AbstractExpression(token), m_isOperator(isOperator), m_functionName(std::move(functionName)),
m_parameterExpressions(std::move(parameterExpressions))
{
}
FunctionCallExpression::~FunctionCallExpression() = default;
Value FunctionCallExpression::execute(const ProgramVariables& variables) const
{
SCP_vector<Value> parameterValues;
parameterValues.reserve(m_parameterExpressions.size());
std::transform(m_parameterExpressions.cbegin(),
m_parameterExpressions.cend(),
std::back_inserter(parameterValues),
[&variables](const std::shared_ptr<AbstractExpression>& expression) { return expression->execute(variables); });
return m_functionDef->implementation(parameterValues);
}
bool FunctionCallExpression::validate(antlr4::Parser* parser, const ParseContext& context)
{
bool valid = true;
for (const auto& paramExpression : m_parameterExpressions) {
valid &= paramExpression->validate(parser, context);
}
if (!valid) {
// Exit early if there were errors since the values below are meaningless otherwise
return false;
}
Assertion(m_isOperator, "Non-operator functions are not supported yet!");
SCP_vector<ValueType> parameterTypes;
std::transform(m_parameterExpressions.cbegin(),
m_parameterExpressions.cend(),
std::back_inserter(parameterTypes),
[](const std::shared_ptr<AbstractExpression>& expression) { return expression->getExpressionType(); });
const auto functionDef = FunctionManager::instance().findOperator(m_functionName, parameterTypes);
if (functionDef == nullptr) {
SCP_stringstream paramListStream;
if (!parameterTypes.empty()) {
paramListStream << "<" << TypeDefinition::forValueType(parameterTypes.front()).getName() << ">";
for (auto iter = parameterTypes.cbegin() + 1; iter != parameterTypes.cend(); ++iter) {
paramListStream << ", <" << TypeDefinition::forValueType(*iter).getName() << ">";
}
}
parser->notifyErrorListeners(m_token,
SCP_string("Could not find a definition for the ") + (m_isOperator ? "operator" : "function") + " '" +
m_functionName + "' with parameters (" + paramListStream.str() + ")",
nullptr);
return false;
}
m_functionDef = functionDef;
return true;
}
ValueType FunctionCallExpression::determineReturnType() const
{
return m_functionDef->returnType;
}
void FunctionCallExpression::validationDone()
{
AbstractExpression::validationDone();
// We no longer need this so we can save some memory
m_functionName.clear();
m_functionName.shrink_to_fit();
for (const auto& paramExpression : m_parameterExpressions) {
paramExpression->validationDone();
}
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,38 +0,0 @@
#pragma once
#include "AbstractExpression.h"
#include "actions/expression/FunctionManager.h"
#include "actions/expression/Value.h"
namespace actions {
namespace expression {
namespace nodes {
class FunctionCallExpression : public AbstractExpression {
public:
FunctionCallExpression(antlr4::Token* token,
bool isOperator,
SCP_string functionName,
SCP_vector<std::shared_ptr<AbstractExpression>> parameterExpressions);
~FunctionCallExpression() override;
Value execute(const ProgramVariables& variables) const override;
bool validate(antlr4::Parser* parser, const ParseContext& context) override;
void validationDone() override;
protected:
ValueType determineReturnType() const override;
private:
bool m_isOperator;
SCP_string m_functionName;
const FunctionDefinition* m_functionDef = nullptr;
SCP_vector<std::shared_ptr<AbstractExpression>> m_parameterExpressions;
};
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,30 +0,0 @@
#include "LiteralExpression.h"
namespace actions {
namespace expression {
namespace nodes {
LiteralExpression::LiteralExpression(antlr4::Token* token, Value literalValue)
: AbstractExpression(token), m_literalValue(std::move(literalValue))
{
}
LiteralExpression::~LiteralExpression() = default;
Value LiteralExpression::execute(const ProgramVariables& /*variables*/) const
{
return m_literalValue;
}
bool LiteralExpression::validate(antlr4::Parser* /*parser*/, const ParseContext& /*context*/)
{
// Literals are always valid
return true;
}
ValueType LiteralExpression::determineReturnType() const
{
return m_literalValue.getType();
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,28 +0,0 @@
#pragma once
#include "AbstractExpression.h"
#include "actions/expression/Value.h"
namespace actions {
namespace expression {
namespace nodes {
class LiteralExpression : public AbstractExpression {
public:
LiteralExpression(antlr4::Token* token, Value literalValue);
~LiteralExpression() override;
Value execute(const ProgramVariables& variables) const override;
bool validate(antlr4::Parser* parser, const ParseContext& context) override;
protected:
ValueType determineReturnType() const override;
private:
Value m_literalValue;
};
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,108 +0,0 @@
#include "RandomRangeExpression.h"
#include "actions/expression/TypeDefinition.h"
#include "utils/RandomRange.h"
namespace actions {
namespace expression {
namespace nodes {
namespace {
template <typename T>
Value executeHelper(const Value& leftVal, const Value& rightVal)
{
auto leftContentVal = leftVal.get<T>();
auto rightContentVal = rightVal.get<T>();
if (leftContentVal == rightContentVal) {
// no need to do random stuff here
return Value(rightContentVal);
}
if (rightContentVal < leftContentVal) {
// We can fix this issue
std::swap(leftContentVal, rightContentVal);
}
// Might be a bit inefficient not to cache this somehow but the bounds can be dynamic
return Value(util::UniformRange<T>(leftContentVal, rightContentVal).next());
}
} // namespace
RandomRangeExpression::RandomRangeExpression(antlr4::Token* token,
std::shared_ptr<AbstractExpression> leftExpression,
std::shared_ptr<AbstractExpression> rightExpression)
: AbstractExpression(token), m_leftExpression(std::move(leftExpression)),
m_rightExpression(std::move(rightExpression))
{
}
RandomRangeExpression::~RandomRangeExpression() = default;
Value RandomRangeExpression::execute(const ProgramVariables& variables) const
{
const auto leftVal = m_leftExpression->execute(variables);
const auto rightVal = m_rightExpression->execute(variables);
if (leftVal.getType() == ValueType::Integer) {
return executeHelper<int>(leftVal, rightVal);
} else {
return executeHelper<float>(leftVal, rightVal);
}
}
bool RandomRangeExpression::validate(antlr4::Parser* parser, const ParseContext& context)
{
bool valid = true;
valid &= m_leftExpression->validate(parser, context);
valid &= m_rightExpression->validate(parser, context);
if (!valid) {
// Exit early if there were errors since the values below are meaningless otherwise
return false;
}
const auto leftType = m_leftExpression->getExpressionType();
const auto rightType = m_rightExpression->getExpressionType();
const auto& leftTypedef = TypeDefinition::forValueType(leftType);
const auto& rightTypedef = TypeDefinition::forValueType(rightType);
// Both values must be the same
if (leftType != rightType) {
parser->notifyErrorListeners(m_rightExpression->getToken(),
"Inconsistent types for random range. Must be the same but got <" + leftTypedef.getName() + "> and <" +
rightTypedef.getName() + ">.",
nullptr);
return false;
}
// And we only support floats or integers
if (leftType != ValueType::Float && leftType != ValueType::Integer) {
parser->notifyErrorListeners(m_leftExpression->getToken(),
"Invalid parameter type for random range. Must be <Float> or <Integer> but got <" + leftTypedef.getName() +
">.",
nullptr);
return false;
}
// Everything is fine.
return true;
}
ValueType RandomRangeExpression::determineReturnType() const
{
// Return type is the same as the contained return types
return m_leftExpression->getExpressionType();
}
void RandomRangeExpression::validationDone()
{
AbstractExpression::validationDone();
m_leftExpression->validationDone();
m_rightExpression->validationDone();
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,30 +0,0 @@
#pragma once
#include "AbstractExpression.h"
namespace actions {
namespace expression {
namespace nodes {
class RandomRangeExpression : public AbstractExpression {
public:
RandomRangeExpression(antlr4::Token* token,
std::shared_ptr<AbstractExpression> leftExpression,
std::shared_ptr<AbstractExpression> rightExpression);
~RandomRangeExpression() override;
Value execute(const ProgramVariables& variables) const override;
bool validate(antlr4::Parser* parser, const ParseContext& context) override;
void validationDone() override;
protected:
ValueType determineReturnType() const override;
private:
std::shared_ptr<AbstractExpression> m_leftExpression;
std::shared_ptr<AbstractExpression> m_rightExpression;
};
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,69 +0,0 @@
#include "VariableReferenceExpression.h"
namespace actions {
namespace expression {
namespace nodes {
VariableReferenceExpression::VariableReferenceExpression(SCP_vector<SCP_string> references,
SCP_vector<antlr4::Token*> referenceTokens)
: AbstractExpression(referenceTokens.back()), m_references(std::move(references)),
m_referenceTokens(std::move(referenceTokens))
{
}
VariableReferenceExpression::~VariableReferenceExpression() = default;
Value VariableReferenceExpression::execute(const ProgramVariables& variables) const
{
return variables.getValue(m_fullVariablePath);
}
bool VariableReferenceExpression::validate(antlr4::Parser* parser, const ParseContext& context)
{
// Start out in the global scope
auto currentScope = &context.variables;
SCP_string currentScopeName("<global>");
for (size_t i = 0; i < m_references.size() - 1; ++i) {
const auto nextScope = currentScope->getScope(m_references[i]);
if (nextScope == nullptr) {
parser->notifyErrorListeners(m_referenceTokens[i],
"Could not find scope " + m_references[i] + " in scope " + currentScopeName + ".",
nullptr);
return false;
}
currentScope = nextScope;
currentScopeName = m_references[i];
}
auto variableType = currentScope->getMemberType(m_references.back());
if (variableType == ValueType::Invalid) {
parser->notifyErrorListeners(m_referenceTokens.back(),
"Could not find variable " + m_references.back() + " in scope " + currentScopeName + ".",
nullptr);
return false;
}
// Cache this so we don't duplicate all this code in determineReturnType()
m_variableType = variableType;
m_fullVariablePath = ProgramVariables::getMemberName(m_references);
return true;
}
ValueType VariableReferenceExpression::determineReturnType() const
{
return m_variableType;
}
void VariableReferenceExpression::validationDone()
{
AbstractExpression::validationDone();
// Clear these since they are not necessary anymore
m_references.clear();
m_referenceTokens.clear();
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,32 +0,0 @@
#pragma once
#include "AbstractExpression.h"
namespace actions {
namespace expression {
namespace nodes {
class VariableReferenceExpression : public AbstractExpression {
public:
VariableReferenceExpression(const SCP_vector<SCP_string> references,
SCP_vector<antlr4::Token*> referenceTokens);
~VariableReferenceExpression() override;
Value execute(const ProgramVariables& variables) const override;
bool validate(antlr4::Parser* parser, const ParseContext& context) override;
void validationDone() override;
protected:
ValueType determineReturnType() const override;
private:
ValueType m_variableType = ValueType::Invalid;
SCP_string m_fullVariablePath;
SCP_vector<SCP_string> m_references;
SCP_vector<antlr4::Token*> m_referenceTokens;
};
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,87 +0,0 @@
#include "VectorConstructorExpression.h"
#include "actions/expression/TypeDefinition.h"
namespace actions {
namespace expression {
namespace nodes {
VectorConstructorExpression::VectorConstructorExpression(antlr4::Token* token,
std::shared_ptr<AbstractExpression> xExpression,
std::shared_ptr<AbstractExpression> yExpression,
std::shared_ptr<AbstractExpression> zExpression)
: AbstractExpression(token), m_xExpression(std::move(xExpression)), m_yExpression(std::move(yExpression)),
m_zExpression(std::move(zExpression))
{
}
VectorConstructorExpression::~VectorConstructorExpression() = default;
Value VectorConstructorExpression::execute(const ProgramVariables& variables) const
{
auto xValue = m_xExpression->execute(variables);
auto yValue = m_yExpression->execute(variables);
auto zValue = m_zExpression->execute(variables);
vec3d vecVal;
vecVal.xyz.x = xValue.getFloat();
vecVal.xyz.y = yValue.getFloat();
vecVal.xyz.z = zValue.getFloat();
return Value(vecVal);
}
bool VectorConstructorExpression::validate(antlr4::Parser* parser, const ParseContext& context)
{
bool valid = true;
valid &= m_xExpression->validate(parser, context);
valid &= m_yExpression->validate(parser, context);
valid &= m_zExpression->validate(parser, context);
if (!valid) {
// Exit early if there were errors since the values below are meaningless otherwise
return false;
}
if (!checkTypeWithImplicitConversion(m_xExpression->getExpressionType(), ValueType::Float)) {
const auto& typeDef = TypeDefinition::forValueType(m_xExpression->getExpressionType());
parser->notifyErrorListeners(m_xExpression->getToken(),
"Invalid value type for vector constructor. Expected <Float>, got <" + typeDef.getName() + ">",
nullptr);
valid = false;
}
if (!checkTypeWithImplicitConversion(m_yExpression->getExpressionType(), ValueType::Float)) {
const auto& typeDef = TypeDefinition::forValueType(m_yExpression->getExpressionType());
parser->notifyErrorListeners(m_yExpression->getToken(),
"Invalid value type for vector constructor. Expected <Float>, got <" + typeDef.getName() + ">",
nullptr);
valid = false;
}
if (!checkTypeWithImplicitConversion(m_zExpression->getExpressionType(), ValueType::Float)) {
const auto& typeDef = TypeDefinition::forValueType(m_zExpression->getExpressionType());
parser->notifyErrorListeners(m_zExpression->getToken(),
"Invalid value type for vector constructor. Expected <Float>, got <" + typeDef.getName() + ">",
nullptr);
valid = false;
}
return valid;
}
ValueType VectorConstructorExpression::determineReturnType() const
{
// No need to look at the expressions here since we will always be a vector
return ValueType::Vector;
}
void VectorConstructorExpression::validationDone()
{
AbstractExpression::validationDone();
m_xExpression->validationDone();
m_yExpression->validationDone();
m_zExpression->validationDone();
}
} // namespace nodes
} // namespace expression
} // namespace actions
@@ -1,34 +0,0 @@
#pragma once
#include "AbstractExpression.h"
#include "actions/expression/Value.h"
namespace actions {
namespace expression {
namespace nodes {
class VectorConstructorExpression : public AbstractExpression {
public:
VectorConstructorExpression(antlr4::Token* token,
std::shared_ptr<AbstractExpression> xExpression,
std::shared_ptr<AbstractExpression> yExpression,
std::shared_ptr<AbstractExpression> zExpression);
~VectorConstructorExpression() override;
Value execute(const ProgramVariables& variables) const override;
bool validate(antlr4::Parser* parser, const ParseContext& context) override;
void validationDone() override;
protected:
ValueType determineReturnType() const override;
private:
std::shared_ptr<AbstractExpression> m_xExpression;
std::shared_ptr<AbstractExpression> m_yExpression;
std::shared_ptr<AbstractExpression> m_zExpression;
};
} // namespace nodes
} // namespace expression
} // namespace actions
-79
View File
@@ -1,79 +0,0 @@
#include "MoveToSubmodel.h"
#include "math/vecmat.h"
#include "parse/parselo.h"
#include "ship/ship.h"
#include <utility>
namespace actions {
namespace types {
flagset<ProgramContextFlags> MoveToSubmodel::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{ProgramContextFlags::HasObject, ProgramContextFlags::HasSubobject};
}
MoveToSubmodel::MoveToSubmodel(expression::TypedActionExpression<ValueType> subObjectExpression)
: m_subObjectExpression(std::move(subObjectExpression))
{
}
MoveToSubmodel::~MoveToSubmodel() = default;
ActionResult MoveToSubmodel::execute(ProgramLocals& locals) const
{
// The calling code should ensure that this never happens
Assertion(locals.hostSubobject >= 0, "Did not have a valid host subobject.");
auto instance = object_get_model_instance(locals.host.objp);
Assertion(instance != -1, "Model instances are required if a host subobject is specified.");
auto pmi = model_get_instance(instance);
auto pm = model_get(pmi->model_num);
const auto destinationSubObject = m_subObjectExpression.execute(locals.variables);
bool goToParent = false;
if (destinationSubObject == "<parent>") {
goToParent = true;
}
if (goToParent) {
// Special case when we simply want to go to our parent without explicitly specifying its name
auto parentSubobject = pm->submodel[locals.hostSubobject].parent;
if (parentSubobject < 0) {
Warning(LOCATION,
"Current program subobject %s on model %s has no parent!",
pm->submodel[locals.hostSubobject].name,
pm->filename);
return ActionResult::Errored;
}
// We have a valid parent so this move will work properly
locals.hostSubobject = parentSubobject;
return ActionResult::Finished;
}
// We need to do a linear search for the right subobject
for (int i = 0; i < pm->n_models; ++i) {
const auto submodel = pm->submodel[i];
if (subsystem_stricmp(destinationSubObject.c_str(), submodel.name) == 0) {
// Found something!
locals.hostSubobject = i;
return ActionResult::Finished;
}
}
Warning(LOCATION, "Could not find subobject %s in model %s!", destinationSubObject.c_str(), pm->filename);
return ActionResult::Errored;
}
std::unique_ptr<Action> MoveToSubmodel::clone() const
{
return std::unique_ptr<Action>(new MoveToSubmodel(*this));
}
} // namespace types
} // namespace actions
-29
View File
@@ -1,29 +0,0 @@
#pragma once
#include "globalincs/flagset.h"
#include "actions/Action.h"
#include "actions/expression/ActionExpression.h"
namespace actions {
namespace types {
class MoveToSubmodel : public Action {
public:
using ValueType = SCP_string;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
explicit MoveToSubmodel(expression::TypedActionExpression<ValueType> subObjectExpression);
~MoveToSubmodel() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<ValueType> m_subObjectExpression;
};
} // namespace types
} // namespace actions
@@ -1,76 +0,0 @@
#include "ParticleEffectAction.h"
#include "math/vecmat.h"
#include "parse/parselo.h"
#include "ship/ship.h"
#include <utility>
namespace actions {
namespace types {
flagset<ProgramContextFlags> ParticleEffectAction::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{ProgramContextFlags::HasObject};
}
ParticleEffectAction::ParticleEffectAction(expression::TypedActionExpression<ValueType> effectExpression)
: m_effectExpression(std::move(effectExpression))
{
}
ParticleEffectAction::~ParticleEffectAction() = default;
ActionResult ParticleEffectAction::execute(ProgramLocals& locals) const
{
auto effectIdx = particle::ParticleManager::get()->getEffectByName(m_effectExpression.execute(locals.variables));
if (!effectIdx.isValid()) {
// In case the parsing code failed
return ActionResult::Errored;
}
using namespace particle;
auto source = ParticleManager::get()->createSource(effectIdx);
vec3d local_pos;
matrix local_orient;
if (locals.hostSubobject != -1) {
auto instance = object_get_model_instance(locals.host.objp);
Assertion(instance != -1, "Model instances are required if a host subobject is specified.");
auto pmi = model_get_instance(instance);
auto pm = model_get(pmi->model_num);
find_submodel_instance_point_orient(&local_pos,
&local_orient,
pm,
pmi,
locals.hostSubobject,
&locals.localPosition,
&locals.localOrient);
} else {
local_pos = locals.localPosition;
local_orient = locals.localOrient;
}
local_pos += locals.variables.getValue({"locals", "position"}).getVector();
auto direction = locals.variables.getValue({"locals", "direction"}).getVector();
source.moveToObject(locals.host.objp, &local_pos);
source.setOrientationFromNormalizedVec(&direction, true);
source.finish();
return ActionResult::Finished;
}
std::unique_ptr<Action> ParticleEffectAction::clone() const
{
return std::unique_ptr<Action>(new ParticleEffectAction(*this));
}
} // namespace types
} // namespace actions
-29
View File
@@ -1,29 +0,0 @@
#pragma once
#include "actions/Action.h"
#include "actions/expression/ActionExpression.h"
#include "particle/ParticleManager.h"
namespace actions {
namespace types {
class ParticleEffectAction : public Action {
public:
using ValueType = SCP_string;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
explicit ParticleEffectAction(expression::TypedActionExpression<ValueType> effectExpression);
~ParticleEffectAction() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<ValueType> m_effectExpression;
};
} // namespace types
} // namespace actions
-65
View File
@@ -1,65 +0,0 @@
//
//
#include "PlaySoundAction.h"
#include "ship/ship.h"
#include <utility>
namespace actions {
namespace types {
flagset<ProgramContextFlags> PlaySoundAction::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{ProgramContextFlags::HasObject};
}
PlaySoundAction::PlaySoundAction(expression::TypedActionExpression<ValueType> soundIdExpression)
: m_soundIdExpression(std::move(soundIdExpression))
{
}
PlaySoundAction::~PlaySoundAction() = default;
ActionResult PlaySoundAction::execute(ProgramLocals& locals) const
{
vec3d local_pos;
matrix local_orient;
if (locals.hostSubobject != -1) {
auto instance = object_get_model_instance(locals.host.objp);
Assertion(instance != -1, "Model instances are required if a host subobject is specified.");
auto pmi = model_get_instance(instance);
auto pm = model_get(pmi->model_num);
find_submodel_instance_point_orient(&local_pos,
&local_orient,
pm,
pmi,
locals.hostSubobject,
&locals.localPosition,
&locals.localOrient);
} else {
local_pos = locals.localPosition;
local_orient = locals.localOrient;
}
local_pos += locals.variables.getValue({"locals", "position"}).getVector();
vec3d global_pos;
vm_vec_unrotate(&global_pos, &local_pos, &locals.host.objp->orient);
global_pos += locals.host.objp->pos;
const auto soundId = gamesnd_get_by_name(m_soundIdExpression.execute(locals.variables).c_str());
// Sound is not attached to the host but the object sound system currently only supports persistent sounds
snd_play_3d(gamesnd_get_game_sound(soundId), &global_pos, &Eye_position);
return ActionResult::Finished;
}
std::unique_ptr<Action> PlaySoundAction::clone() const
{
return std::unique_ptr<Action>(new PlaySoundAction(*this));
}
} // namespace types
} // namespace actions
-28
View File
@@ -1,28 +0,0 @@
#pragma once
#include "actions/Action.h"
#include "actions/expression/ActionExpression.h"
#include "gamesnd/gamesnd.h"
namespace actions {
namespace types {
class PlaySoundAction : public Action {
public:
using ValueType = SCP_string;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
explicit PlaySoundAction(expression::TypedActionExpression<ValueType> soundIdExpression);
~PlaySoundAction() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<ValueType> m_soundIdExpression;
};
} // namespace types
} // namespace actions
-39
View File
@@ -1,39 +0,0 @@
#include "SetDirectionAction.h"
#include "math/vecmat.h"
#include "parse/parselo.h"
#include <utility>
namespace actions {
namespace types {
flagset<ProgramContextFlags> SetDirectionAction::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{};
}
SetDirectionAction::SetDirectionAction(expression::TypedActionExpression<vec3d> newDirExpression)
: m_newDirExpression(std::move(newDirExpression))
{
}
SetDirectionAction::~SetDirectionAction() = default;
ActionResult SetDirectionAction::execute(ProgramLocals& locals) const
{
auto dir = m_newDirExpression.execute(locals.variables);
vm_vec_normalize_safe(&dir);
locals.variables.setValue({"locals", "direction"}, expression::Value(dir));
return ActionResult::Finished;
}
std::unique_ptr<Action> SetDirectionAction::clone() const
{
return std::unique_ptr<Action>(new SetDirectionAction(*this));
}
} // namespace types
} // namespace actions
-27
View File
@@ -1,27 +0,0 @@
#pragma once
#include "actions/Action.h"
#include "actions/expression/ActionExpression.h"
namespace actions {
namespace types {
class SetDirectionAction : public Action {
public:
using ValueType = vec3d;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
SetDirectionAction(expression::TypedActionExpression<ValueType> newDirExpression);
~SetDirectionAction() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<ValueType> m_newDirExpression;
};
} // namespace types
} // namespace actions
-34
View File
@@ -1,34 +0,0 @@
#include "SetPositionAction.h"
#include "parse/parselo.h"
#include <utility>
namespace actions {
namespace types {
flagset<ProgramContextFlags> SetPositionAction::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{};
}
SetPositionAction::SetPositionAction(expression::TypedActionExpression<ValueType> newPositionExpression)
: m_newPosExpression(std::move(newPositionExpression))
{
}
SetPositionAction::~SetPositionAction() = default;
ActionResult SetPositionAction::execute(ProgramLocals& locals) const
{
locals.variables.setValue({"locals", "position"}, expression::Value(m_newPosExpression.execute(locals.variables)));
return ActionResult::Finished;
}
std::unique_ptr<Action> SetPositionAction::clone() const
{
return std::unique_ptr<Action>(new SetPositionAction(*this));
}
} // namespace types
} // namespace actions
-28
View File
@@ -1,28 +0,0 @@
#pragma once
#include "actions/Action.h"
#include "actions/expression/ActionExpression.h"
namespace actions {
namespace types {
class SetPositionAction : public Action {
public:
using ValueType = vec3d;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
SetPositionAction(expression::TypedActionExpression<ValueType> newPositionExpression);
~SetPositionAction() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<vec3d> m_newPosExpression;
};
} // namespace types
} // namespace actions
-48
View File
@@ -1,48 +0,0 @@
#include "WaitAction.h"
#include "io/timer.h"
#include "parse/parselo.h"
namespace actions {
namespace types {
flagset<ProgramContextFlags> WaitAction::getRequiredExecutionContextFlags()
{
return flagset<ProgramContextFlags>{};
}
WaitAction::WaitAction(expression::TypedActionExpression<float> waitTimeExpression)
: _waitTimeExpression(std::move(waitTimeExpression))
{
}
WaitAction::~WaitAction() = default;
ActionResult WaitAction::execute(actions::ProgramLocals& locals) const
{
if (!timestamp_valid(locals.waitTimestamp)) {
auto waitTime = _waitTimeExpression.execute(locals.variables);
// Catch errors in the expression
if (waitTime < 0.001f) {
waitTime = 0.001f;
}
locals.waitTimestamp = timestamp(fl2i(waitTime * TIMESTAMP_FREQUENCY));
}
if (!timestamp_elapsed(locals.waitTimestamp)) {
// Wait until the timestamp is elapsed
return ActionResult::Wait;
}
// Timestamp is elapsed. The timestamp is elapsed so that timestamp_valid above returns false for the next wait
// action
locals.waitTimestamp = 0;
return ActionResult::Finished;
}
std::unique_ptr<Action> WaitAction::clone() const
{
return std::unique_ptr<Action>(new WaitAction(*this));
}
} // namespace types
} // namespace actions
-29
View File
@@ -1,29 +0,0 @@
#pragma once
#include "actions/Action.h"
#include "actions/common.h"
#include "actions/expression/ActionExpression.h"
#include "utils/RandomRange.h"
namespace actions {
namespace types {
class WaitAction : public Action {
public:
using ValueType = float;
static flagset<ProgramContextFlags> getRequiredExecutionContextFlags();
explicit WaitAction(expression::TypedActionExpression<ValueType> waitTimeExpression);
~WaitAction() override;
ActionResult execute(ProgramLocals& locals) const override;
std::unique_ptr<Action> clone() const override;
private:
expression::TypedActionExpression<ValueType> _waitTimeExpression;
};
} // namespace types
} // namespace actions
+15 -16
View File
@@ -18,7 +18,8 @@
#include "ship/ship.h"
SCP_vector<char *> Goal_target_names;
int Total_goal_target_names = 0;
char Goal_target_names[MAX_GOAL_TARGET_NAMES][NAME_LENGTH];
ai_info Ai_info[MAX_AI_INFO];
ai_info *Player_ai;
@@ -36,7 +37,8 @@ int ai_get_slot(int shipnum)
return i;
}
Error( LOCATION, "Couldn't get AI slot, please tell a coder!");
Warning( LOCATION, "Couldn't get AI slot" );
Int3();
return -1;
}
@@ -80,25 +82,22 @@ void set_wingnum(int objnum, int wingnum)
Ai_info[ai_index].wing = wingnum;
}
const char *ai_get_goal_target_name(const char *name, int *index)
char *ai_get_goal_target_name(const char *name, int *index)
{
Assertion(name != nullptr && index != nullptr, "Arguments cannot be null!");
Assert(name != NULL);
Assert(index != NULL);
int i;
for (int i = 0; i < static_cast<int>(Goal_target_names.size()); ++i) {
for (i=0; i < Total_goal_target_names; i++)
if (!stricmp(name, Goal_target_names[i])) {
*index = i;
return Goal_target_names[i];
}
}
*index = static_cast<int>(Goal_target_names.size());
Goal_target_names.push_back(vm_strdup(name));
return Goal_target_names[*index];
}
void ai_clear_goal_target_names()
{
for (auto ptr : Goal_target_names)
vm_free(ptr);
Goal_target_names.clear();
Assert(Total_goal_target_names < MAX_GOAL_TARGET_NAMES);
Assertion(strlen(name) <= NAME_LENGTH - 1, "Goal target name %s is too long. Needs to be 31 characters or less.", name);
i = Total_goal_target_names++;
strcpy_s(Goal_target_names[i], name);
*index = i;
return Goal_target_names[i];
}
+16 -19
View File
@@ -70,7 +70,6 @@ extern ai_flag_name Ai_flag_names[];
#define AITTV_FAST (1<<0) // Turn fast, not slowed down based on skill level.
#define AITTV_VIA_SEXP (1<<1) // Goober5000 - via sexp
#define AITTV_IGNORE_BANK (1<<2) // Goober5000 - ignore bank when turning
#define AITTV_SLOW_BANK_ACCEL (1<<3) // Asteroth - used by formation flying
#define KAMIKAZE_HULL_ON_DEATH -1000.0f // Hull strength ship gets set to if it crash-dies.
@@ -84,7 +83,7 @@ typedef struct ai_goal {
fix time; // time at which this goal was issued.
int priority; // how important is this goal -- number 0 - 100
const char *target_name; // name of the thing that this goal acts upon
char *target_name; // name of the thing that this goal acts upon
int target_name_index; // index of goal_target_name in Goal_target_names[][]
waypoint_list *wp_list; // waypoints that this ship might fly.
int target_instance; // instance of thing this ship might be chasing (currently only used for weapons; note, not the same as objnum!)
@@ -94,17 +93,19 @@ typedef struct ai_goal {
// (AIGF_DOCKER_INDEX_VALID and AIGF_DOCKEE_INDEX_VALID tell us to use indexes; otherwise we use names)
// these are the dockpoints used on the docker and dockee ships, not the ships themselves
union {
const char *name;
char *name;
int index;
} docker;
union {
const char *name;
char *name;
int index;
} dockee;
} ai_goal;
#define MAX_GOAL_TARGET_NAMES 100
#define AIM_CHASE 0
#define AIM_EVADE 1
#define AIM_GET_BEHIND 2
@@ -183,7 +184,6 @@ typedef struct ai_class {
// Submode definitions.
// Note: These need to be renamed to be of the form: AIS_mode_xxxx
// Cyborg17 -- If you add submodes for AI_CHASE, you *have to* add entries to Submode_text[] in aicode.cpp
#define SM_CONTINUOUS_TURN 1 // takes parm: vector_id {0..3 = right, -right, up, -up}
#define SM_ATTACK 2
#define SM_EVADE_SQUIGGLE 3
@@ -472,8 +472,8 @@ typedef struct ai_info {
fix avoid_check_timestamp; // timestamp at which to next check for having to avoid ship
vec3d big_collision_normal; // Global normal of collision with big ship. Helps find direction to fly away from big ship. Set for each collision.
vec3d big_recover_1_direction; // A relative direction to fly towards when recovering from collision with a big ship, stage 1.
vec3d big_recover_2_pos; // Global point to fly towards when recovering from collision with a big ship, stage 2.
vec3d big_recover_pos_1; // Global point to fly towards when recovering from collision with a big ship, stage 1.
vec3d big_recover_pos_2; // Global point to fly towards when recovering from collision with a big ship, stage 2.
int big_recover_timestamp; // timestamp at which it's OK to re-enter stage 1.
int abort_rearm_timestamp; // time at which this rearm should be aborted in a multiplayer game.
@@ -487,10 +487,7 @@ typedef struct ai_info {
flagset<AI::Maneuver_Override_Flags> ai_override_flags; // flags for marking ai overrides from sexp or lua systems
control_info ai_override_ci; // ai override control info
int ai_override_lat_timestamp; // mark for when to end the current lateral maneuver override
int ai_override_rot_timestamp; // mark for when to end the current rotational maneuver override
int form_obj_slotnum; // for flying in formation object mode, the position in the formation
int ai_override_timestamp; // mark for when to end the current override
} ai_info;
// Goober5000
@@ -516,6 +513,8 @@ typedef struct {
#define BURST_DURATION 500 // decay time over which Player->damage_this_burst falls from MAX_BURST_DAMAGE to 0
extern int Mission_all_attack; // !0 means all teams attack all teams.
extern int Total_goal_target_names;
extern char Goal_target_names[MAX_GOAL_TARGET_NAMES][NAME_LENGTH];
extern void update_ai_info_for_hit(int hitter_obj, int hit_obj);
extern void ai_frame_all(void);
@@ -557,8 +556,7 @@ void ai_process( object * obj, int ai_index, float frametime );
int get_wingnum(int objnum);
void set_wingnum(int objnum, int wingnum);
const char *ai_get_goal_target_name(const char *name, int *index);
void ai_clear_goal_target_names();
char *ai_get_goal_target_name(const char *name, int *index);
extern void init_ai_system(void);
extern void ai_attack_object(object *attacker, object *attacked, ship_subsys *ssp, int ship_info_index = -1);
@@ -571,7 +569,7 @@ extern void ai_do_default_behavior(object *obj);
extern void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags);
extern void ai_ship_hit(object *objp_ship, object *hit_objp, vec3d *hit_normal);
extern void ai_ship_destroy(int shipnum);
extern void ai_turn_towards_vector(vec3d *dest, object *objp, vec3d *slide_vec, vec3d *rel_pos, float bank_override, int flags, vec3d *rvec = nullptr, vec3d* turnrate_mod = nullptr);
extern void ai_turn_towards_vector(vec3d *dest, object *objp, float turn_time, vec3d *slide_vec, vec3d *rel_pos, float bank_override, int flags, vec3d *rvec = nullptr, int sexp_flags = 0);
extern void init_ai_object(int objnum);
extern void ai_init(void); // Call this one to parse ai.tbl.
extern void ai_level_init(void); // Call before each level to reset AI
@@ -584,7 +582,8 @@ extern void ai_update_danger_weapon(int objnum, int weapon_objnum);
// called externally from MissionParse.cpp to position ships in wings upon arrival into the
// mission.
extern void get_absolute_wing_pos(vec3d *result_pos, object *leader_objp, int wingnum, int wing_index, bool formation_object_flag, bool autopilot = false);
extern void get_absolute_wing_pos( vec3d *result_pos, object *leader_objp, int wing_index, int formation_object_flag);
extern void get_absolute_wing_pos_autopilot( vec3d *result_pos, object *leader_objp, int wing_index, int formation_object_flag);
// Interface from goals code to AI. Set ship to guard. *objp guards *other_objp
extern void ai_set_guard_object(object *objp, object *other_objp);
@@ -622,7 +621,7 @@ extern int might_collide_with_ship(object *obj1, object *obj2, float dot_to_enem
extern int ai_fire_primary_weapon(object *objp); //changed to return weather it fired-Bobboau
extern int ai_fire_secondary_weapon(object *objp);
extern float ai_get_weapon_dist(ship_weapon *swp);
extern void turn_towards_point(object *objp, vec3d *point, vec3d *slide_vec, float bank_override, matrix* target_orient = nullptr, int flags = 0);
extern void turn_towards_point(object *objp, vec3d *point, vec3d *slide_vec, float bank_override);
extern int ai_maybe_fire_afterburner(object *objp, ai_info *aip);
extern void set_predicted_enemy_pos(vec3d *predicted_enemy_pos, object *pobjp, vec3d *enemy_pos, vec3d *enemy_vel, ai_info *aip);
@@ -634,7 +633,7 @@ void set_predicted_enemy_pos_turret(vec3d *predicted_enemy_pos, vec3d *gun_pos,
// function to change rearm status for ai ships (called from sexpression code)
extern void ai_set_rearm_status( int team, int new_status );
extern void ai_good_secondary_time( int team, int weapon_index, int num_weapons, const char *shipname );
extern void ai_good_secondary_time( int team, int weapon_index, int num_weapons, char *shipname );
extern void ai_do_objects_docked_stuff(object *docker, int docker_point, object *dockee, int dockee_point, bool update_clients = true);
extern void ai_do_objects_undocked_stuff( object *docker, object *dockee );
@@ -667,6 +666,4 @@ void ai_update_aim(ai_info *aip);
//SUSHI: Random evasive sidethrust
void do_random_sidethrust(ai_info *aip, ship_info *sip);
void ai_formation_object_recalculate_slotnums(int form_objnum, int exiting_objnum = -1);
#endif
+2 -14
View File
@@ -63,9 +63,7 @@ namespace AI {
Dont_bank_when_turning, // maps to CIF_DONT_BANK_WHEN_TURNING
Dont_clamp_max_velocity, // maps to CIF_DONT_CLAMP_MAX_VELOCITY
Instantaneous_acceleration, // maps to CIF_INSTANTANEOUS_ACCELERATION
Lateral_never_expire, // don't clear the lateral maneuver when the timestamp is up
Rotational_never_expire, // don't clear the rotational maneuver when the timestamp is up
Dont_override_old_maneuvers,// doesn't clear any previous maneuvers
Never_expire, // don't clear the maneuver when the timestamp is up
NUM_VALUES
};
@@ -86,17 +84,13 @@ namespace AI {
Assist_scoring_scales_with_damage,
Beams_damage_weapons,
Big_ships_can_attack_beam_turrets_on_untargeted_ships,
Check_comms_for_non_player_ships,
Disable_linked_fire_penalty,
Disable_player_secondary_doublefire,
Disable_ai_secondary_doublefire,
Disable_weapon_damage_scaling,
Dont_insert_random_turret_fire_delay,
Fix_ai_class_bug,
Fix_ai_path_order_bug,
Fix_heat_seeker_stealth_bug,
Fix_linked_primary_bug,
Fix_ramming_stationary_targets_bug,
Force_beam_turret_fov,
Free_afterburner_use,
Glide_decay_requires_thrust,
@@ -120,19 +114,13 @@ namespace AI {
Smart_secondary_weapon_selection,
Smart_shield_management,
Smart_subsystem_targeting_for_turrets,
Strict_turret_tagged_only_targeting,
Strict_turred_tagged_only_targeting,
Support_dont_add_primaries, //Prevents support ship from equipping new primary as requested in http://scp.indiegames.us/mantis/view.php?id=3198
Turrets_ignore_target_radius,
Use_actual_primary_range,
Use_subsystem_path_point_radii,
Use_additive_weapon_velocity,
Use_newtonian_dampening,
Use_only_single_fov_for_turrets,
No_turning_directional_bias,
Use_axial_turnrate_differences,
nonshielded_ships_can_manage_ets,
Better_collision_avoidance,
Require_exact_los,
NUM_VALUES
};
+3 -61
View File
@@ -7,12 +7,11 @@
#include "ai/ai_profiles.h"
#include "ai/aibig.h"
#include "globalincs/pstypes.h"
#include "def_files/def_files.h"
#include "ai/ai_profiles.h"
#include "globalincs/pstypes.h"
#include "localization/localize.h"
#include "mod_table/mod_table.h"
#include "parse/parselo.h"
#include "ship/ship.h"
#include "weapon/weapon.h"
@@ -372,16 +371,10 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$navigation subsystem governs warpout capability:", AI::Profile_Flags::Navigation_subsys_governs_warp);
set_flag(profile, "$check communications for non-player ships:", AI::Profile_Flags::Check_comms_for_non_player_ships);
set_flag(profile, "$ignore lower bound for minimum speed of docked ship:", AI::Profile_Flags::No_min_dock_speed_cap);
set_flag(profile, "$disable linked fire penalty:", AI::Profile_Flags::Disable_linked_fire_penalty);
set_flag(profile, "$disable player secondary doublefire:", AI::Profile_Flags::Disable_player_secondary_doublefire);
set_flag(profile, "$disable ai secondary doublefire:", AI::Profile_Flags::Disable_ai_secondary_doublefire);
set_flag(profile, "$disable weapon damage scaling:", AI::Profile_Flags::Disable_weapon_damage_scaling);
set_flag(profile, "$use additive weapon velocity:", AI::Profile_Flags::Use_additive_weapon_velocity);
@@ -398,8 +391,6 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$fix linked primary weapon decision bug:", AI::Profile_Flags::Fix_linked_primary_bug);
set_flag(profile, "$fix ramming stationary targets bug:", AI::Profile_Flags::Fix_ramming_stationary_targets_bug);
set_flag(profile, "$prevent turrets targeting too distant bombs:", AI::Profile_Flags::Prevent_targeting_bombs_beyond_range);
set_flag(profile, "$smart subsystem targeting for turrets:", AI::Profile_Flags::Smart_subsystem_targeting_for_turrets);
@@ -446,8 +437,6 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$support don't add primaries:", AI::Profile_Flags::Support_dont_add_primaries);
set_flag(profile, "$firing requires exact los:", AI::Profile_Flags::Require_exact_los);
profile->ai_path_mode = AI_PATH_MODE_NORMAL;
if (optional_string("$ai path mode:"))
{
@@ -465,7 +454,7 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$fix ai path order bug:", AI::Profile_Flags::Fix_ai_path_order_bug);
set_flag(profile, "$strict turret-tagged-only targeting:", AI::Profile_Flags::Strict_turret_tagged_only_targeting);
set_flag(profile, "$strict turret-tagged-only targeting:", AI::Profile_Flags::Strict_turred_tagged_only_targeting);
set_flag(profile, "$aspect bomb invulnerability fix:", AI::Profile_Flags::Aspect_invulnerability_fix);
@@ -475,18 +464,6 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$use actual primary range:", AI::Profile_Flags::Use_actual_primary_range);
if (optional_string("$override radius for subsystem path points:")) {
int path_radii;
stuff_int(&path_radii);
if (path_radii >= Minimum_subsystem_path_pt_dist) {
profile->subsystem_path_radii = path_radii;
} else {
mprintf(("Warning: \"$override radius for subsystem path points:\" should be >= %i (read %i). Value will not be used. ", Minimum_subsystem_path_pt_dist, path_radii));
}
}
set_flag(profile, "$use POF radius for subsystem path points:", AI::Profile_Flags::Use_subsystem_path_point_radii);
profile->bay_arrive_speed_mult = 1.0f;
profile->bay_depart_speed_mult = 1.0f;
if (optional_string("$bay arrive speed multiplier:")) {
@@ -513,21 +490,7 @@ void parse_ai_profiles_tbl(const char *filename)
stuff_boolean(&temp);
profile->flags.set(AI::Profile_Flags::Allow_primary_link_at_start, !temp);
}
if (optional_string("$lead indicator second-order prediction factor:")) {
stuff_float(&profile->second_order_lead_predict_factor);
if (profile->second_order_lead_predict_factor > 1 || profile->second_order_lead_predict_factor < 0) {
mprintf(("Warning: \"$lead indicator second-order prediction factor\" must be 0 - 1, resetting to 0.\"\n"));
profile->second_order_lead_predict_factor = 0;
}
}
set_flag(profile, "$no directional bias for missile and ship turning:", AI::Profile_Flags::No_turning_directional_bias);
set_flag(profile, "$respect ship axial turnrate differences:", AI::Profile_Flags::Use_axial_turnrate_differences);
set_flag(profile, "$ships with no shields can manage ETS:", AI::Profile_Flags::nonshielded_ships_can_manage_ets);
set_flag(profile, "$better combat collision avoidance for fightercraft:", AI::Profile_Flags::Better_collision_avoidance);
// if we've been through once already and are at the same place, force a move
if (saved_Mp && (saved_Mp == Mp))
@@ -601,10 +564,8 @@ void ai_profile_t::reset()
flags.reset();
ai_path_mode = 0;
subsystem_path_radii = 0;
bay_arrive_speed_mult = 0;
bay_depart_speed_mult = 0;
second_order_lead_predict_factor = 0;
for (int i = 0; i < NUM_SKILL_LEVELS; ++i) {
max_incoming_asteroids[i] = 0;
@@ -663,23 +624,4 @@ void ai_profile_t::reset()
for (int i = 0; i <= MAX_DETAIL_LEVEL; ++i) {
detail_distance_mult[i] = 0;
}
// via Github #2332, enable bugfixes if we are targeting version 20 and up
if (mod_supports_version(20, 0, 0)) {
flags.set(AI::Profile_Flags::Huge_turret_weapons_ignore_bombs);
flags.set(AI::Profile_Flags::Fix_linked_primary_bug);
flags.set(AI::Profile_Flags::Prevent_targeting_bombs_beyond_range);
flags.set(AI::Profile_Flags::Fix_heat_seeker_stealth_bug);
flags.set(AI::Profile_Flags::Allow_vertical_dodge);
flags.set(AI::Profile_Flags::Fix_ai_class_bug);
flags.set(AI::Profile_Flags::Ai_guards_specific_ship_in_wing);
flags.set(AI::Profile_Flags::Fix_ai_path_order_bug);
flags.set(AI::Profile_Flags::Aspect_invulnerability_fix);
flags.set(AI::Profile_Flags::Use_actual_primary_range);
flags.set(AI::Profile_Flags::nonshielded_ships_can_manage_ets);
}
// this flag has been enabled ever since 3.7.2
if (mod_supports_version(3, 7, 2)) {
flags.set(AI::Profile_Flags::Fix_ramming_stationary_targets_bug);
}
}
-6
View File
@@ -97,17 +97,11 @@ public:
int ai_path_mode;
// radii to use for the radius for subsystem path points and default value --wookieejedi
int subsystem_path_radii;
// Ships flying bay paths will gradually accelerate/decelerate instead of
// flying the whole path at max speed
float bay_arrive_speed_mult;
float bay_depart_speed_mult;
// How much 0-1 of a second-order lead prediction factor to add to lead indicators. Affects only the HUD indicator, and autoaim.
float second_order_lead_predict_factor;
void reset();
};
+11 -44
View File
@@ -370,8 +370,7 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
float dot = 1.0f, min_dot;
object *target_objp;
auto shipp = &Ships[Pl_objp->instance];
aip = &Ai_info[shipp->ai_index];
aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
if ( aip->target_objnum < 0 )
return 0;
@@ -383,8 +382,7 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
float dist;
// Get models of both source and target
polymodel *pm = model_get( Ship_info[shipp->ship_info_index].model_num );
polymodel_instance *pmi = model_get_instance( shipp->model_instance_num );
polymodel *pm = model_get( Ship_info[Ships[Pl_objp->instance].ship_info_index].model_num );
polymodel *pm_t = model_get( Ship_info[Ships[target_objp->instance].ship_info_index].model_num );
// Necessary sanity check
@@ -405,8 +403,8 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
aip->path_subsystem_next_check = timestamp(1500);
// get world pos of eye (stored in geye)
ep = &(pm->view_positions[shipp->current_viewpoint]);
model_instance_find_world_point( &geye, &ep->pnt, pm, pmi, 0, &Pl_objp->orient, &Pl_objp->pos );
ep = &(pm->view_positions[Ships[Pl_objp->instance].current_viewpoint]);
model_find_world_point( &geye, &ep->pnt, pm->id, 0, &Pl_objp->orient, &Pl_objp->pos );
// get world pos of subsystem
vm_vec_unrotate(&gsubpos, &aip->targeted_subsys->system_info->pnt, &En_objp->orient);
@@ -433,6 +431,7 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
min_dot = (target_objp->phys_info.fspeed > 5.0f?MIN_DOT_TO_ATTACK_MOVING_SUBSYS:MIN_DOT_TO_ATTACK_SUBSYS);
if ( (checked_sight && ((!subsys_in_sight) || (dot < min_dot)) ) ) {
aip->path_goal_dist = 5;
subsys_path_num = aip->targeted_subsys->system_info->path_num;
if ( ((aip->path_start) == -1 || (aip->mp_index != subsys_path_num)) && subsys_path_num < pm_t->n_paths ) {
// maybe create a new path
@@ -462,41 +461,9 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
Assert(aip->path_length >= 2);
dist = vm_vec_dist_quick(&Path_points[aip->path_start+aip->path_length-2].pos, &Pl_objp->pos);
// distance setting --wookieejedi
if ( aip->path_cur >= (aip->path_start+aip->path_length-1) ) {
// register that path is done and reset goal distance to default
aip->path_goal_dist = Default_subsystem_path_pt_dist;
path_done=1;
}
// if not done then set path distances based on specified options
else {
bool found_point = false;
// 1. use radii of path points if specified
if (aip->ai_profile_flags[AI::Profile_Flags::Use_subsystem_path_point_radii]) {
// need a valid path and point in model to use pof specified radius
int path_num = aip->targeted_subsys->system_info->path_num;
if ((0 <= path_num) && (path_num < pm_t->n_paths)) {
// need a valid place in the path
if ((0 <= aip->path_cur) && (aip->path_cur < aip->path_length)) {
float path_point_radius = pm_t->paths[path_num].verts[aip->path_cur].radius;
int goal_dist = fl2i(path_point_radius);
// only set if >= Minimum path distance specified in aibig.h
if (goal_dist >= Minimum_subsystem_path_pt_dist) {
aip->path_goal_dist = goal_dist;
found_point = true;
}
}
}
}
// 2. use radii value in ai_profiles table if specified and no valid point found
if (!found_point && The_mission.ai_profile->subsystem_path_radii) {
aip->path_goal_dist = The_mission.ai_profile->subsystem_path_radii;
}
// 3. use default radii value if no valid point or specified radii
else {
aip->path_goal_dist = Default_subsystem_path_pt_dist;
}
}
min_dot = (target_objp->phys_info.fspeed > 5.0f?MIN_DOT_TO_ATTACK_MOVING_SUBSYS:MIN_DOT_TO_ATTACK_SUBSYS);
if ( (checked_sight && subsys_in_sight) && (dot > min_dot) ) {
@@ -664,8 +631,8 @@ void ai_big_chase_attack(ai_info *aip, ship_info *sip, vec3d *enemy_pos, float d
compute_desired_rvec(rvec, enemy_pos, &Pl_objp->pos);
else
rvec = NULL;
ai_turn_towards_vector(enemy_pos, Pl_objp, nullptr, rel_pos, 0.0f, 0, rvec);
ai_turn_towards_vector(enemy_pos, Pl_objp, sip->srotation_time, nullptr, rel_pos, 0.0f, 0, rvec);
// calc range of primary weapon
weapon_travel_dist = ai_get_weapon_dist(&Ships[Pl_objp->instance].weapons);
@@ -739,7 +706,7 @@ void ai_big_chase_ct()
extern void ai_select_secondary_weapon(object *objp, ship_weapon *swp, int priority1 = -1, int priority2 = -1);
extern float set_secondary_fire_delay(ai_info *aip, ship *shipp, weapon_info *swip, bool burst);
extern void ai_choose_secondary_weapon(object *objp, ai_info *aip, object *en_objp);
extern int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vec3d *goal_point, float delta_time, float time_scale = 1.f);
extern int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vec3d *goal_point, float delta_time);
extern void maybe_cheat_fire_synaptic(object *objp);
@@ -1330,7 +1297,7 @@ void ai_big_strafe_attack()
if (aip->ai_flags[AI::AI_Flags::Kamikaze]) {
if (target_dist < 1200.0f) {
ai_turn_towards_vector(&target_pos, Pl_objp, nullptr, nullptr, 0.0f, 0);
ai_turn_towards_vector(&target_pos, Pl_objp, Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time, nullptr, nullptr, 0.0f, 0);
accelerate_ship(aip, 1.0f);
if ((target_dist < 400.0f) && ai_maybe_fire_afterburner(Pl_objp, aip)) {
afterburners_start(Pl_objp);
@@ -1455,7 +1422,7 @@ void ai_big_strafe_glide_attack()
vm_vec_sub(&targetToAttacker, &Pl_objp->pos, &target_objp->pos);
matrix orient;
vm_vector_2_matrix(&orient, &targetToAttacker, NULL, NULL);
vm_vec_random_in_circle(&tangentPoint, &target_objp->pos, &orient, target_objp->radius + GLIDE_STRAFE_DISTANCE, true);
vm_vec_random_in_circle(&tangentPoint, &target_objp->pos, &orient, target_objp->radius + GLIDE_STRAFE_DISTANCE, 1);
//Get tangent point in coords relative to ship, scale it up so the actual goal point is far away, then put back in world coords
vm_vec_sub2(&tangentPoint, &Pl_objp->pos);
vm_vec_scale(&tangentPoint, 1000.0f);
@@ -1707,7 +1674,7 @@ void ai_big_strafe()
break;
default:
Error(LOCATION, "Ai_big_strafe() just tried to use an illegal submode. Go tell a coder!");
Int3(); // Illegal submode for AIM_STRAFE
break;
}
-4
View File
@@ -27,10 +27,6 @@ void ai_big_strafe_maybe_attack_turret(const object *ship_objp, const object *we
void ai_big_pick_attack_point(object *objp, object *attacker_objp, vec3d *attack_point, float fov=1.0f);
void ai_big_pick_attack_point_turret(object *objp, ship_subsys *ssp, vec3d *gpos, vec3d *gvec, vec3d *attack_point, float weapon_travel_dist, float fov=1.0f);
// default distance for following subsystem path points --wookieejedi
// the value is 5 because that was the original value specified in ai_big_maybe_follow_subsys_path()
const int Default_subsystem_path_pt_dist = 5;
const int Minimum_subsystem_path_pt_dist = 1;
#endif
+405 -740
View File
File diff suppressed because it is too large. Load diff
+54 -75
View File
@@ -25,8 +25,6 @@
#include "ship/ship.h"
#include "weapon/weapon.h"
// Just a reference to this struct being for looking up a ship's team in TVT
struct ship_registry_entry;
// all ai goals dealt with in this code are goals that are specified through
// sexpressions in the mission file. They are either specified as part of a
@@ -136,48 +134,28 @@ const char *Ai_goal_text(int goal)
return NULL;
}
void ai_maybe_add_form_goal(wing* wingp)
// function to maybe add the form on my wing goal for a player's starting wing. Called when a player wing arrives.
void ai_maybe_add_form_goal( wing *wingp )
{
// Cyborg17 - Changes from the client would just get overridden by the server anyway
// might as well keep them more closely in sync.
if (MULTIPLAYER_CLIENT) {
return;
}
int j;
// iterate through the ship_index list of this wing and check for orders. We will do
// this for all ships in the wing instead of on a wing only basis in case some ships
// in the wing actually have different orders than others
for (j = 0; j < wingp->current_count; j++) {
ai_info* aip;
for ( j = 0; j < wingp->current_count; j++ ) {
ai_info *aip;
Assert(wingp->ship_index[j] != -1); // get Allender
Assert( wingp->ship_index[j] != -1 ); // get Allender
aip = &Ai_info[Ships[wingp->ship_index[j]].ai_index];
// don't process a Player_ship
if (Objects[Ships[aip->shipnum].objnum].flags[Object::Object_Flags::Player_ship]) {
// don't process Player_ship
if ( aip == Player_ai )
continue;
}
// need to add a form on my wing goal here. Ships are always forming on the player's wing.
// it is sufficient enough to check the first goal entry to see if it has a valid goal
if (aip->goals[0].ai_mode == AI_GOAL_NONE) {
// Need to have a more specific target in multi, or they may end up trying to target standalone placeholder.
// So form on their team leader. In dogfight, all player-slot ai die, so just exclude.
if (MULTIPLAYER_MASTER && !(Netgame.type_flags & NG_TYPE_DOGFIGHT)) {
int wingnum;
if (Netgame.type_flags & NG_TYPE_TEAM) {
const ship_registry_entry* ship_regp = ship_registry_get(Ships[wingp->ship_index[j]].ship_name);
wingnum = TVT_wings[ship_regp->p_objp->team];
ai_add_ship_goal_player(AIG_TYPE_PLAYER_SHIP, AI_GOAL_FORM_ON_WING, -1, Ships[Wings[wingnum].ship_index[Wings[wingnum].special_ship]].ship_name, aip);
} else {
wingnum = Starting_wings[0];
ai_add_ship_goal_player(AIG_TYPE_PLAYER_SHIP, AI_GOAL_FORM_ON_WING, -1, Ships[Wings[wingnum].ship_index[Wings[wingnum].special_ship]].ship_name, aip);
}
} else if (!(Game_mode & GM_MULTIPLAYER)) {
ai_add_ship_goal_player(AIG_TYPE_PLAYER_SHIP, AI_GOAL_FORM_ON_WING, -1, Player_ship->ship_name, aip);
}
if ( aip->goals[0].ai_mode == AI_GOAL_NONE ) {
// need to add a form on my wing goal here. Ships are always forming on the player's wing.
ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, AI_GOAL_FORM_ON_WING, -1, Player_ship->ship_name, aip );
}
}
}
@@ -295,12 +273,15 @@ void ai_clear_ship_goals( ai_info *aip )
// add scripting hook for 'On Goals Cleared' --wookieejedi
Script_system.SetHookObject("Ship", &Objects[Ships[aip->shipnum].objnum]);
Script_system.RunCondition(CHA_ONGOALSCLEARED);
Script_system.RemHookVars({"Ship"});
Script_system.RemHookVars(1, "Ship");
}
void ai_clear_wing_goals( wing *wingp )
void ai_clear_wing_goals( int wingnum )
{
int i;
wing *wingp = &Wings[wingnum];
//p_object *objp;
// clear the goals for all ships in the wing
for (i = 0; i < wingp->current_count; i++) {
@@ -311,13 +292,15 @@ void ai_clear_wing_goals( wing *wingp )
}
// clear out the goals for the wing now
// clear out the goals for the wing now
for (i = 0; i < MAX_AI_GOALS; i++) {
wingp->ai_goals[i].ai_mode = AI_GOAL_NONE;
wingp->ai_goals[i].signature = -1;
wingp->ai_goals[i].priority = -1;
wingp->ai_goals[i].flags.reset();
}
}
// routine which marks a wing goal as being complete. We get the wingnum and a pointer to the goal
@@ -327,7 +310,7 @@ void ai_clear_wing_goals( wing *wingp )
void ai_mission_wing_goal_complete( int wingnum, ai_goal *remove_goalp )
{
int mode, submode, priority, i;
const char *name;
char *name;
ai_goal *aigp;
wing *wingp;
@@ -405,7 +388,7 @@ void ai_goal_purge_invalid_goals( ai_goal *aigp, ai_goal *goal_list, ai_info *ai
{
int i, j;
ai_goal *purge_goal;
const char *name;
char *name;
int mode, ship_index, wingnum;
// get locals for easer access
@@ -852,10 +835,11 @@ void ai_add_wing_goal_player( int type, int mode, int submode, char *shipname, i
void ai_add_goal_sub_sexp( int sexp, int type, ai_goal *aigp, char *actor_name )
{
int node, dummy, op;
char *text;
Assert ( Sexp_nodes[sexp].first != -1 );
node = Sexp_nodes[sexp].first;
op = get_operator_const( node );
text = CTEXT(node);
aigp->signature = Ai_goal_signature++;
@@ -864,6 +848,8 @@ void ai_add_goal_sub_sexp( int sexp, int type, ai_goal *aigp, char *actor_name )
aigp->type = type;
aigp->flags.reset();
op = get_operator_const( text );
switch (op) {
case OP_AI_WAYPOINTS_ONCE:
@@ -1032,7 +1018,7 @@ void ai_add_goal_sub_sexp( int sexp, int type, ai_goal *aigp, char *actor_name )
}
if ( aigp->priority > MAX_GOAL_PRIORITY ) {
nprintf (("AI", "bashing sexpression priority of goal %s from %d to %d.\n", CTEXT(node), aigp->priority, MAX_GOAL_PRIORITY));
nprintf (("AI", "bashing sexpression priority of goal %s from %d to %d.\n", text, aigp->priority, MAX_GOAL_PRIORITY));
aigp->priority = MAX_GOAL_PRIORITY;
}
@@ -1097,9 +1083,14 @@ int ai_remove_goal_sexp_sub( int sexp, ai_goal* aigp )
int goalsubmode = -1;
/* Sexp node */
int node = Sexp_nodes[sexp].first;
int node = -1;
/* The operator to use */
int op = get_operator_const( node );
char* op_text = NULL;
int op = -1;
node = Sexp_nodes[ sexp ].first;
op_text = CTEXT( node );
op = get_operator_const( op_text );
/* We now need to determine what the mode and submode values are*/
switch( op )
@@ -1226,10 +1217,11 @@ int ai_remove_goal_sexp_sub( int sexp, ai_goal* aigp )
}
// code to add ai goals to wings.
void ai_remove_wing_goal_sexp(int sexp, wing *wingp)
void ai_remove_wing_goal_sexp(int sexp, int wingnum)
{
int i;
int goalindex = -1;
wing *wingp = &Wings[wingnum];
// add the ai goal for any ship that is currently arrived in the game (only if fred isn't running)
if ( !Fred_running ) {
@@ -1260,9 +1252,10 @@ void ai_add_ship_goal_sexp( int sexp, int type, ai_info *aip )
}
// code to add ai goals to wings.
void ai_add_wing_goal_sexp(int sexp, int type, wing *wingp)
void ai_add_wing_goal_sexp(int sexp, int type, int wingnum)
{
int i;
wing *wingp = &Wings[wingnum];
// add the ai goal for any ship that is currently arrived in the game (only if fred isn't running)
if ( !Fred_running ) {
@@ -1420,17 +1413,21 @@ int ai_mission_goal_achievable( int objnum, ai_goal *aigp )
{
ship *shipp = &Ships[objp->instance];
// always valid if has working subspace drive, not disabled, and not limited by subsystem strength
if ( ship_can_warp_full_check(shipp) )
// always valid if has subspace drive
if (!(shipp->flags[Ship::Ship_Flags::No_subspace_drive]))
return AI_GOAL_ACHIEVABLE;
// if we can't warp, we can only depart if the ship (or its wing) departs to a fighter bay and the mothership is present
if (ship_can_bay_depart(shipp)) {
return AI_GOAL_ACHIEVABLE;
}
else {
return AI_GOAL_NOT_KNOWN;
// if no subspace drive, only valid if our mothership is present
// check that we have a mothership and that we can depart to it
if (shipp->departure_location == DEPART_AT_DOCK_BAY)
{
int anchor_shipnum = ship_name_lookup(Parse_names[shipp->departure_anchor]);
if (anchor_shipnum >= 0 && ship_useful_for_departure(anchor_shipnum, shipp->departure_path_mask))
return AI_GOAL_ACHIEVABLE;
}
return AI_GOAL_NOT_KNOWN;
}
@@ -1655,35 +1652,25 @@ int ai_mission_goal_achievable( int objnum, ai_goal *aigp )
}
else
{
auto ship_entry = ship_registry_get(aigp->target_name);
if (!ship_entry)
{
status = SHIP_STATUS_UNKNOWN;
}
// goal ship is currently in mission
else if (ship_entry->status == ShipStatus::PRESENT)
if ( ship_name_lookup( aigp->target_name ) != -1 )
{
status = SHIP_STATUS_ARRIVED;
}
// goal ship is still on the arrival list
else if (ship_entry->status == ShipStatus::NOT_YET_PRESENT)
else if ( mission_check_ship_yet_to_arrive(aigp->target_name) )
{
status = SHIP_STATUS_NOT_ARRIVED;
}
// goal ship has left the area
else if (ship_entry->status == ShipStatus::EXITED)
else if ( ship_find_exited_ship_by_name(aigp->target_name) != -1 )
{
status = SHIP_STATUS_GONE;
}
else
{
status = SHIP_STATUS_UNKNOWN;
}
if (status == SHIP_STATUS_UNKNOWN)
{
mprintf(("Potentially incorrect behaviour in AI goal for ship %s: Ship %s could not be found among currently active, departed, or yet-to-arrive ships.\nPlease check the mission file.\n", Ships[objp->instance].ship_name, aigp->target_name));
status = SHIP_STATUS_UNKNOWN;
}
}
@@ -2118,13 +2105,7 @@ void ai_process_mission_orders( int objnum, ai_info *aip )
// if this object was flying in formation off of another object, remove the flag that tells him
// to do this. The form-on-my-wing command is removed from the goal list as soon as it is called, so
// we are safe removing this bit here.
int old_form_objnum = -1;
if (aip->ai_flags[AI::AI_Flags::Formation_object]) {
// save who he was following so we can tell any others
// who are following to re-organize
old_form_objnum = aip->goal_objnum;
aip->ai_flags.remove(AI::AI_Flags::Formation_object);
}
aip->ai_flags.remove(AI::AI_Flags::Formation_object);
// Goober5000 - we may want to use AI for the player
// AL 3-7-98: If this is a player ship, and the goal is not a formation goal, then do a quick out
@@ -2390,8 +2371,6 @@ void ai_process_mission_orders( int objnum, ai_info *aip )
break;
}
if (old_form_objnum != -1)
ai_formation_object_recalculate_slotnums(old_form_objnum);
}
void ai_update_goal_references(ai_goal *goals, int type, const char *old_name, const char *new_name)
+3 -3
View File
@@ -102,11 +102,11 @@ extern int ai_goal_num(ai_goal *goals);
// adds goals to ships/wing through sexpressions
extern void ai_add_ship_goal_scripting(int mode, int submode, int priority, char *shipname, ai_info *aip);
extern void ai_add_ship_goal_sexp( int sexp, int type, ai_info *aip );
extern void ai_add_wing_goal_sexp( int sexp, int type, wing *wingp );
extern void ai_add_wing_goal_sexp( int sexp, int type, int wingnum );
extern void ai_add_goal_sub_sexp( int sexp, int type, ai_goal *aigp, char *actor_name );
extern int ai_remove_goal_sexp_sub( int sexp, ai_goal* aigp );
extern void ai_remove_wing_goal_sexp( int sexp, wing *wingp );
extern void ai_remove_wing_goal_sexp(int sexp, int wingnum);
// adds goals to ships/sings through player orders
extern void ai_add_ship_goal_player( int type, int mode, int submode, char *shipname, ai_info *aip );
@@ -114,7 +114,7 @@ extern void ai_add_wing_goal_player( int type, int mode, int submode, char *ship
extern void ai_remove_ship_goal( ai_info *aip, int index );
extern void ai_clear_ship_goals( ai_info *aip );
extern void ai_clear_wing_goals( wing *wingp );
extern void ai_clear_wing_goals( int wingnum );
extern void ai_copy_mission_wing_goal( ai_goal *aigp, ai_info *aip );
+2 -5
View File
@@ -26,12 +26,9 @@ int object_is_targetable(object *target, ship *viewer);
int num_nearby_fighters(int enemy_team_mask, vec3d *pos, float threshold);
//Returns true if OK for *aip to fire its current weapon at its current target.
int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip, int secondary_bank, ship_subsys* turret);
//Returns true if *aip has a line of sight to its current target.
bool check_los(int objnum, int target_objnum, float threshold, int primary_bank, int secondary_bank, ship_subsys* turret);
int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip);
//Does all the stuff needed to aim and fire a turret.
void ai_fire_from_turret(ship *shipp, ship_subsys *ss);
void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum);
#endif
+306 -297
View File
@@ -382,16 +382,10 @@ weapon_info *get_turret_weapon_wip(ship_weapon *swp, int weapon_num)
Assert(weapon_num < MAX_SHIP_WEAPONS);
Assert(weapon_num >= 0);
int wi_index;
if(weapon_num >= MAX_SHIP_PRIMARY_BANKS)
wi_index = swp->secondary_bank_weapons[weapon_num - MAX_SHIP_PRIMARY_BANKS];
return &Weapon_info[swp->secondary_bank_weapons[weapon_num - MAX_SHIP_PRIMARY_BANKS]];
else
wi_index = swp->primary_bank_weapons[weapon_num];
if (wi_index < 0)
return nullptr;
else
return &Weapon_info[wi_index];
return &Weapon_info[swp->primary_bank_weapons[weapon_num]];
}
int get_turret_weapon_next_fire_stamp(ship_weapon *swp, int weapon_num)
@@ -405,17 +399,6 @@ int get_turret_weapon_next_fire_stamp(ship_weapon *swp, int weapon_num)
return swp->next_primary_fire_stamp[weapon_num];
}
void set_turret_weapon_next_fire_stamp(ship_weapon *swp, int weapon_num, int delta_ms)
{
Assert(weapon_num < MAX_SHIP_WEAPONS);
Assert(weapon_num >= 0);
if (weapon_num >= MAX_SHIP_PRIMARY_BANKS)
swp->next_secondary_fire_stamp[weapon_num - MAX_SHIP_PRIMARY_BANKS] = timestamp(delta_ms);
else
swp->next_primary_fire_stamp[weapon_num] = timestamp(delta_ms);
}
/**
* Returns the longest-ranged weapon on a turret
*
@@ -615,7 +598,7 @@ void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
// however if this is removed turrets still track targets but don't fire at them (which looks silly)
if (eeo->eeo_flags & EEOF_TAGGED_ONLY) {
if (!ship_is_tagged(objp) &&
( (The_mission.ai_profile->flags[AI::Profile_Flags::Strict_turret_tagged_only_targeting]) ||
( (The_mission.ai_profile->flags[AI::Profile_Flags::Strict_turred_tagged_only_targeting]) ||
( !(objp->type == OBJ_WEAPON) && !(turret_weapon_has_flags(&eeo->turret_subsys->weapons, Weapon::Info_Flags::Spawn))) )) {
return;
}
@@ -792,6 +775,29 @@ void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
} // end asteroid selection
}
/**
* Is target beam valid?
*
* @return 0 only if objnum is beam protected and turret is beam turret
*/
int is_target_beam_valid(ship_weapon *swp, object *objp)
{
// check if turret has beam weapon
if (all_turret_weapons_have_flags(swp, Weapon::Info_Flags::Beam)) {
if (objp->flags[Object::Object_Flags::Beam_protected]) {
return 0;
}
if (all_turret_weapons_have_flags(swp, Weapon::Info_Flags::Huge)) {
if (objp->type == OBJ_SHIP && !(Ship_info[Ships[objp->instance].ship_info_index].is_big_or_huge()) ) {
return 0;
}
}
}
return 1;
}
/**
* Given an object and an enemy team, return the index of the nearest enemy object.
*
@@ -1067,7 +1073,8 @@ int get_nearest_turret_objnum(int turret_parent_objnum, ship_subsys *turret_subs
evaluate_obj_as_target(objp, &eeo);
}
// next highest priority is attacking ship
Assert(eeo.nearest_attacker_objnum < 0 || is_target_beam_valid(swp, &Objects[eeo.nearest_attacker_objnum]));
// next highest priority is attacking ship
if ( eeo.nearest_attacker_objnum != -1 ) { // next highest priority is an attacking ship
return eeo.nearest_attacker_objnum;
}
@@ -1266,24 +1273,26 @@ void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vec3d *gpos
{
vec3d * gun_pos;
model_subsystem *tp = ssp->system_info;
polymodel_instance *pmi = model_get_instance(Ships[objp->instance].model_instance_num);
polymodel *pm = model_get(pmi->model_num);
//ship_model_start(objp);
gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
model_instance_find_world_point(gpos, gun_pos, pm, pmi, tp->turret_gun_sobj, &objp->orient, &objp->pos);
//model_find_world_point(gpos, gun_pos, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
model_instance_find_world_point(gpos, gun_pos, Ships[objp->instance].model_instance_num, tp->turret_gun_sobj, &objp->orient, &objp->pos);
if (use_angles) {
model_instance_find_world_dir(gvec, &tp->turret_norm, pm, pmi, tp->turret_gun_sobj, &objp->orient);
model_instance_find_world_dir(gvec, &tp->turret_norm, Ships[objp->instance].model_instance_num, tp->turret_gun_sobj, &objp->orient);
} else if (tp->flags[Model::Subsystem_Flags::Share_fire_direction]) {
vec3d avg, tmp_pos, tmp_target, enemy_point, turret_norm;
vm_vec_avg_n(&avg, tp->turret_num_firing_points, tp->turret_firing_point);
model_instance_find_world_point(&tmp_pos, &avg, pm, pmi, tp->turret_gun_sobj, &objp->orient, &objp->pos);
model_instance_find_world_point(&tmp_pos, &avg, Ships[objp->instance].model_instance_num, tp->turret_gun_sobj, &objp->orient, &objp->pos);
if (targetp == nullptr) {
ship* shipp = &Ships[Objects[ssp->parent_objnum].instance];
Assertion(ssp->turret_enemy_objnum >= 0, "The turret enemy object number %d for %s on ship name %s is invalid.", ssp->turret_enemy_objnum, ssp->sub_name, shipp->ship_name);
Assertion(ssp->turret_enemy_objnum >= 0, "The turret enemy object number %d for %s on ship name %s is invalid.", ssp->turret_enemy_objnum, ssp->sub_name,
(shipp->has_display_name()) ? shipp->display_name.c_str() : shipp->ship_name);
object *lep = &Objects[ssp->turret_enemy_objnum];
int best_weapon_tidx = turret_select_best_weapon(ssp, lep);
@@ -1330,6 +1339,8 @@ void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vec3d *gpos
vm_vec_normalized_dir(gvec, targetp, gpos);
}
//ship_model_stop(objp);
// per firingpoint based changes go here for turrets
}
@@ -1361,11 +1372,9 @@ void turret_ai_update_aim(ai_info *aip, object *En_Objp, ship_subsys *ss)
*
* @return TRUE if caller should use angles in subsequent rotations.
*/
int aifft_rotate_turret(object *objp, ship *shipp, ship_subsys *ss, object *lep, vec3d *predicted_enemy_pos, vec3d *gvec)
int aifft_rotate_turret(ship *shipp, int parent_objnum, ship_subsys *ss, object *objp, object *lep, vec3d *predicted_enemy_pos, vec3d *gvec)
{
int ret_val __UNUSED = 0; // to be used in future, see comment @ end of function
auto pmi = model_get_instance(shipp->model_instance_num);
auto pm = model_get(pmi->model_num);
if (ss->turret_enemy_objnum != -1) {
model_subsystem *tp = ss->system_info;
@@ -1386,7 +1395,7 @@ int aifft_rotate_turret(object *objp, ship *shipp, ship_subsys *ss, object *lep,
// weapon_system_strength scales time enemy in range in 0..1. So, the lower this is, the worse the aiming will be.
weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
ship_get_global_turret_info(objp, tp, &gun_pos, &gun_vec);
ship_get_global_turret_info(&Objects[parent_objnum], tp, &gun_pos, &gun_vec);
//Update "known" position and velocity of target. Only matters if max_aim_update_delay is set.
turret_ai_update_aim(&Ai_info[shipp->ai_index], &Objects[ss->turret_enemy_objnum], ss);
@@ -1417,7 +1426,7 @@ int aifft_rotate_turret(object *objp, ship *shipp, ship_subsys *ss, object *lep,
set_predicted_enemy_pos_turret(predicted_enemy_pos, &gun_pos, objp, &enemy_point, &target_moving_direction, wip->max_speed, ss->turret_time_enemy_in_range * (weapon_system_strength + 1.0f)/2.0f);
//Mess with the turret's accuracy if the weapon system is damaged.
if (weapon_system_strength < Weapon_SS_Threshold_Turret_Inaccuracy) {
if (weapon_system_strength < 0.7f) {
vec3d rand_vec;
static_randvec(Missiontime >> 18, &rand_vec); // Return same random number for two seconds.
@@ -1440,12 +1449,15 @@ int aifft_rotate_turret(object *objp, ship *shipp, ship_subsys *ss, object *lep,
}
if (in_fov) {
ret_val = model_rotate_gun(objp, pm, pmi, tp, predicted_enemy_pos);
ret_val = model_rotate_gun(Ship_info[shipp->ship_info_index].model_num,
tp, &Objects[parent_objnum].orient,
&ss->submodel_info_1.angs, &ss->submodel_info_2.angs,
&Objects[parent_objnum].pos, predicted_enemy_pos, shipp->objnum);
} else if ((tp->flags[Model::Subsystem_Flags::Turret_reset_idle]) &&(timestamp_elapsed(ss->rotation_timestamp))) {
ret_val = model_rotate_gun(objp, pm, pmi, tp, predicted_enemy_pos, true);
ret_val = model_rotate_gun(Ship_info[shipp->ship_info_index].model_num, tp, &Objects[parent_objnum].orient, &ss->submodel_info_1.angs, &ss->submodel_info_2.angs, &Objects[parent_objnum].pos, predicted_enemy_pos, shipp->objnum, true);
}
} else if ((ss->system_info->flags[Model::Subsystem_Flags::Turret_reset_idle]) && (timestamp_elapsed(ss->rotation_timestamp))) {
ret_val = model_rotate_gun(objp, pm, pmi, ss->system_info, predicted_enemy_pos, true);
ret_val = model_rotate_gun(Ship_info[shipp->ship_info_index].model_num, ss->system_info, &Objects[parent_objnum].orient, &ss->submodel_info_1.angs, &ss->submodel_info_2.angs, &Objects[parent_objnum].pos, predicted_enemy_pos, shipp->objnum, true);
}
// by default "ret_val" should be set to 1 for multi-part turrets, and 0 for single-part turrets
@@ -1776,15 +1788,11 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
ai_info *parent_aip;
ship *parent_ship;
float flak_range = 0.0f;
weapon_info *wip;
weapon *wp;
object *objp;
// make sure we actually have a valid weapon
auto wip = get_turret_weapon_wip(&turret->weapons, weapon_num);
if (!wip)
return false;
bool last_shot_in_salvo = true;
if (turret->system_info->flags[Model::Subsystem_Flags::Turret_salvo])
{
if ((turret->turret_next_fire_pos + 1) == (turret->system_info->turret_num_firing_points))
@@ -1803,6 +1811,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
parent_ship = &Ships[Objects[parent_objnum].instance];
wip = get_turret_weapon_wip(&turret->weapons, weapon_num);
int turret_weapon_class = weapon_info_get_index(wip);
#ifndef NDEBUG
@@ -1812,28 +1821,28 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
// should not get this far. check if ship is protected from beam and weapon is type beam
if ( (wip->wi_flags[Weapon::Info_Flags::Beam]) && (tobjp->flags[Object::Object_Flags::Beam_protected]) ) {
nprintf(("Warning","Ship %s is trying to fire beam turret at beam protected ship\n", parent_ship->ship_name));
return false;
Int3();
return 0;
}
// should not get this far. check if ship is protected from flak and weapon is type flak
else if ( (wip->wi_flags[Weapon::Info_Flags::Flak]) && (tobjp->flags[Object::Object_Flags::Flak_protected]) ) {
nprintf(("Warning","Ship %s is trying to fire flak turret at flak protected ship\n", parent_ship->ship_name));
return false;
Int3();
return 0;
}
// should not get this far. check if ship is protected from laser and weapon is type laser
else if ( (wip->subtype == WP_LASER) && (tobjp->flags[Object::Object_Flags::Laser_protected]) ) {
nprintf(("Warning","Ship %s is trying to fire laser turret at laser protected ship\n", parent_ship->ship_name));
return false;
Int3();
return 0;
}
// should not get this far. check if ship is protected from missile and weapon is type missile
else if ( (wip->subtype == WP_MISSILE) && (tobjp->flags[Object::Object_Flags::Missile_protected]) ) {
nprintf(("Warning","Ship %s is trying to fire missile turret at missile protected ship\n", parent_ship->ship_name));
return false;
Int3();
return 0;
}
}
#endif
if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, wip, -1, turret)) {
if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, wip)) {
vm_vector_2_matrix(&turret_orient, turret_fvec, NULL, NULL);
turret->turret_last_fire_direction = *turret_fvec;
@@ -1861,7 +1870,6 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
else
fire_info.target_subsys = NULL;
fire_info.turret = turret;
fire_info.fire_method = BFM_TURRET_FIRED;
// fire a beam weapon
weapon_objnum = beam_fire(&fire_info);
@@ -1874,7 +1882,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
Script_system.SetHookObjects(4, "Ship", &Objects[parent_objnum], "Weapon", nullptr, "Beam", objp, "Target", &Objects[turret->turret_enemy_objnum]);
Script_system.RunCondition(CHA_ONTURRETFIRED, &Objects[parent_objnum]);
Script_system.RemHookVars({"Ship", "Weapon", "Beam", "Target"});
Script_system.RemHookVars(4, "Ship", "Weapon", "Beam", "Target");
}
turret->flags.set(Ship::Subsystem_Flags::Has_fired); //set fired flag for scripting -nike
@@ -2009,7 +2017,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
Script_system.SetHookObjects(4, "Ship", &Objects[parent_objnum], "Weapon", objp, "Beam", nullptr, "Target", &Objects[turret->turret_enemy_objnum]);
Script_system.RunCondition(CHA_ONTURRETFIRED, &Objects[parent_objnum]);
Script_system.RemHookVars({"Ship", "Weapon", "Beam", "Target"});
Script_system.RemHookVars(4, "Ship", "Weapon", "Beam", "Target");
// if the gun is a flak gun
if (wip->wi_flags[Weapon::Info_Flags::Flak]) {
@@ -2073,7 +2081,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
turret->flags.set(Ship::Subsystem_Flags::Has_fired); //set has fired flag for scriptng - nuke
//Fire animation stuff
model_anim_start_type(turret, AnimationTriggerType::TurretFired, ANIMATION_SUBTYPE_ALL, 1);
model_anim_start_type(turret, TRIGGER_TYPE_TURRET_FIRED, ANIMATION_SUBTYPE_ALL, 1);
return true;
}
@@ -2126,7 +2134,7 @@ void turret_swarm_fire_from_turret(turret_swarm_info *tsi)
Script_system.SetHookObjects(4, "Ship", &Objects[tsi->parent_objnum], "Weapon", &Objects[weapon_objnum], "Beam", nullptr, "Target", &Objects[tsi->turret->turret_enemy_objnum]);
Script_system.RunCondition(CHA_ONTURRETFIRED, &Objects[tsi->parent_objnum]);
Script_system.RemHookVars({"Ship", "Weapon", "Beam", "Target"});
Script_system.RemHookVars(4, "Ship", "Weapon", "Beam", "Target");
// muzzle flash?
if (Weapon_info[tsi->weapon_class].muzzle_flash >= 0) {
@@ -2136,7 +2144,7 @@ void turret_swarm_fire_from_turret(turret_swarm_info *tsi)
// maybe sound
if ( Weapon_info[tsi->weapon_class].launch_snd.isValid() ) {
// Don't play turret firing sound if turret sits on player ship... it gets annoying.
if ( tsi->parent_objnum != OBJ_INDEX(Player_obj) || (tsi->turret->flags[Ship::Subsystem_Flags::Play_sound_for_player]) ) {
if ( tsi->parent_objnum != OBJ_INDEX(Player_obj) ) {
snd_play_3d( gamesnd_get_game_sound(Weapon_info[tsi->weapon_class].launch_snd), &turret_pos, &View_position );
}
}
@@ -2160,16 +2168,20 @@ int Num_turrets_fired = 0;
* Given a turret tp and its parent parent_objnum, fire from the turret at its enemy.
*/
extern int Nebula_sec_range;
void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum)
{
float weapon_firing_range;
float WeaponMinRange; // *Weapon minimum firing range -Et1
// *Weapon minimum firing range -Et1
float WeaponMinRange;
vec3d v2e;
object *lep; // Last enemy pointer
model_subsystem *tp = ss->system_info;
ship_weapon *swp = &ss->weapons;
vec3d predicted_enemy_pos = vmd_zero_vector;
object *objp;
//ai_info *aip;
// Reset the points to target value
ss->points_to_target = -1.0f;
@@ -2200,19 +2212,22 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
if (swp->primary_bank_weapons[weap_check] >= 0)
valid_weap = true;
}
if (!valid_weap) {
for (weap_check = 0; (weap_check < ss->weapons.num_secondary_banks) && !valid_weap; weap_check++) {
if (ss->weapons.secondary_bank_weapons[weap_check] >= 0)
valid_weap = true;
}
if (!valid_weap)
return;
}
// Monitor number of calls to ai_fire_from_turret
Num_ai_firing++;
// If beam weapon, check beam free
if ( all_turret_weapons_have_flags(swp, Weapon::Info_Flags::Beam) && !(swp->flags[Ship::Weapon_Flags::Beam_Free]) ) {
return;
}
// Handle turret animation
if (ss->turret_animation_position == MA_POS_SET) {
if ( timestamp_elapsed(ss->turret_animation_done_time) ) {
ss->turret_animation_position = MA_POS_READY;
@@ -2226,43 +2241,45 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
}
}
// AL 09/14/97: ensure ss->turret_enemy_objnum != -1 before setting lep
if ( (ss->turret_enemy_objnum >= 0 && ss->turret_enemy_objnum < MAX_OBJECTS) && (ss->turret_enemy_sig == Objects[ss->turret_enemy_objnum].signature) )
Assert((parent_objnum >= 0) && (parent_objnum < MAX_OBJECTS));
objp = &Objects[parent_objnum];
Assert(objp->type == OBJ_SHIP);
Assert( shipp->objnum == parent_objnum );
// Monitor number of calls to ai_fire_from_turret
Num_ai_firing++;
if ( (ss->turret_enemy_objnum < 0 || ss->turret_enemy_objnum >= MAX_OBJECTS) || (ss->turret_enemy_sig != Objects[ss->turret_enemy_objnum].signature))
{
lep = &Objects[ss->turret_enemy_objnum];
ss->turret_enemy_objnum = -1;
lep = NULL;
}
else
{
ss->turret_enemy_objnum = -1;
lep = nullptr;
lep = &Objects[ss->turret_enemy_objnum];
}
Assert((shipp->objnum >= 0) && (shipp->objnum < MAX_OBJECTS));
int parent_objnum = shipp->objnum;
objp = &Objects[shipp->objnum];
Assert(objp->type == OBJ_SHIP);
//aip = &Ai_info[Ships[objp->instance].ai_index];
// Wanderer - make sure turrets already have all the data
if ( !(tp->flags[Model::Subsystem_Flags::Turret_matrix]) )
{
if (!(tp->turret_gun_sobj == tp->subobj_num))
{
auto pmi = model_get_instance(shipp->model_instance_num);
auto pm = model_get(pmi->model_num);
model_make_turret_matrix(pm, pmi, tp);
model_make_turret_matrix(Ship_info[shipp->ship_info_index].model_num, tp );
}
}
// Use the turret info for all guns, not one gun in particular.
vec3d gvec, gpos;
ship_get_global_turret_info(objp, tp, &gpos, &gvec);
ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
if (tp->flags[Model::Subsystem_Flags::Turret_alt_math]) {
vm_matrix_x_matrix( &ss->world_to_turret_matrix, &objp->orient, &tp->turret_matrix );
vm_matrix_x_matrix( &ss->world_to_turret_matrix, &Objects[parent_objnum].orient, &tp->turret_matrix );
}
// Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
int use_angles = aifft_rotate_turret(objp, shipp, ss, lep, &predicted_enemy_pos, &gvec);
int use_angles = aifft_rotate_turret(shipp, parent_objnum, ss, objp, lep, &predicted_enemy_pos, &gvec);
if ((tp->flags[Model::Subsystem_Flags::Fire_on_target]) && (ss->points_to_target >= 0.0f))
{
@@ -2276,81 +2293,76 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
}
// Don't try to fire beyond weapon_limit_range
// WMC moved the range check to within the loop, but we can still calculate the enemy distance here
//WMC - OTC
//weapon_firing_range = MIN(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
//WMC - build a list of valid weapons. Fire spawns if there are any.
float dist_to_enemy = 0.0f;
if (lep) {
if(lep != NULL) {
if (The_mission.ai_profile->flags[AI::Profile_Flags::Turrets_ignore_target_radius])
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos));
dist_to_enemy = MAX(0,vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos));
else
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius);
dist_to_enemy = MAX(0,vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius);
}
// count the number of enemies, in case we have a spawning weapon
int num_ships_nearby = num_nearby_fighters(iff_get_attackee_mask(obj_team(objp)), &gpos, 1500.0f);
// some flags considering there may be different weapon types on this turret
bool we_did_non_spawning_logic = false;
bool tentative_return = false;
//WMC - go through all valid weapons. Fire spawns if there are any.
int valid_weapons[MAX_SHIP_WEAPONS];
int valid_weapons[MAX_SHIP_PRIMARY_BANKS + MAX_SHIP_SECONDARY_BANKS];
int num_valid = 0;
for (int i = 0; i < MAX_SHIP_WEAPONS; ++i)
weapon_info *wip;
int num_ships_nearby = num_nearby_fighters(iff_get_attackee_mask(obj_team(&Objects[parent_objnum])), &gpos, 1500.0f);
int i;
int secnum = 0;
for(i = 0; i < (MAX_SHIP_WEAPONS); i++)
{
//WMC - Only fire more than once if we have multiple guns flag set.
if (num_valid > 0 && !(tp->flags[Model::Subsystem_Flags::Use_multiple_guns]))
if(num_valid > 0 && !(tp->flags[Model::Subsystem_Flags::Use_multiple_guns]))
break;
// figure out which weapon we are firing, if we even have a valid one
weapon_info *wip = nullptr;
if (i < MAX_SHIP_PRIMARY_BANKS)
if(i < MAX_SHIP_PRIMARY_BANKS)
{
if (i < swp->num_primary_banks && timestamp_elapsed(swp->next_primary_fire_stamp[i]))
wip = &Weapon_info[swp->primary_bank_weapons[i]];
if(i >= swp->num_primary_banks)
{
//set to MAX_SHIP_PRIMARY_BANKS - 1 since i is incremented at the top of the loop
//otherwise, we would pass over the first secondary weapon in the bank
i = MAX_SHIP_PRIMARY_BANKS - 1; //we are done with primaries
continue;
}
if ( !timestamp_elapsed(swp->next_primary_fire_stamp[i]))
{
continue;
}
wip = &Weapon_info[swp->primary_bank_weapons[i]];
}
else
{
int j = i - MAX_SHIP_PRIMARY_BANKS;
if (j < swp->num_secondary_banks && timestamp_elapsed(swp->next_secondary_fire_stamp[j]))
wip = &Weapon_info[swp->secondary_bank_weapons[j]];
secnum = i - MAX_SHIP_PRIMARY_BANKS;
if(secnum >= swp->num_secondary_banks)
break; //we are done.
if ( !timestamp_elapsed(swp->next_secondary_fire_stamp[secnum]))
{
continue;
}
wip = &Weapon_info[swp->secondary_bank_weapons[secnum]];
}
if (!wip)
continue;
// Turret spawn weapons are a special case. They fire if there are enough enemies in the
// immediate area (not necessarily in the turret fov).
// However, if this is a 'smart spawn', just use it like a normal weapon
//If this is a spawning type weapon, shoot it!
//If 'smart spawn' just use it like normal weapons
if ( (wip->wi_flags[Weapon::Info_Flags::Spawn]) && !(wip->wi_flags[Weapon::Info_Flags::Smart_spawn]) )
{
if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
turret_fire_weapon(i, ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
} else {
// Regardless of firing rate, don't check whether should fire for awhile.
if (tp->flags[Model::Subsystem_Flags::Use_multiple_guns])
set_turret_weapon_next_fire_stamp(swp, i, 1000);
else
ss->turret_next_fire_stamp = timestamp(1000);
ss->turret_next_fire_stamp = timestamp(1000); // Regardless of firing rate, don't check whether should fire for awhile.
}
//we're done with this weapon mount
continue;
}
we_did_non_spawning_logic = true; // for the post-loop check
// If beam weapon, check beam free
if (wip->wi_flags[Weapon::Info_Flags::Beam] && !(ss->weapons.flags[Ship::Weapon_Flags::Beam_Free])) {
tentative_return = true;
continue;
}
// the remaining checks in this loop all require a valid lep
if (!lep)
continue;
// Get weapon range
if (wip->wi_flags[Weapon::Info_Flags::Local_ssm])
if(wip->wi_flags[Weapon::Info_Flags::Local_ssm])
{
weapon_firing_range = wip->lssm_lock_range;
weapon_firing_range=wip->lssm_lock_range;
WeaponMinRange = 0.0f;
}
else
@@ -2359,115 +2371,105 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
WeaponMinRange = wip->WeaponMinRange;
}
// if beam weapon in nebula and target not tagged, decrease firing range
if (wip->wi_flags[Weapon::Info_Flags::Beam]) {
if ( !((shipp->tag_left > 0) || (shipp->level2_tag_left > 0)) ) {
if (Nebula_sec_range) {
if (Nebula_sec_range)
{
weapon_firing_range *= BEAM_NEBULA_RANGE_REDUCE_FACTOR;
// *Scale minimum weapon range in nebula -Et1
//Why? - WMC
//Commented this out, because it doesn't make sense - WMC
//WeaponMinRange *= BEAM_NEBULA_RANGE_REDUCE_FACTOR;
}
}
}
// Don't try to fire beyond weapon_limit_range (or within min range)
if (dist_to_enemy < WeaponMinRange || dist_to_enemy > weapon_firing_range) {
// it's possible another weapon is in range, but if not,
// we will end up selecting a new target
continue;
}
if(lep != NULL)
{
if( (dist_to_enemy <= weapon_firing_range) && (dist_to_enemy >= WeaponMinRange) )
{
if ( wip->wi_flags[Weapon::Info_Flags::Huge] ) {
if ( lep->type != OBJ_SHIP ) {
continue;
}
if ( !(Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge()) ) {
continue;
}
}
// If targeted a small ship and have a huge weapon, don't fire. But this shouldn't happen, as a small ship should not get selected.
if ( wip->wi_flags[Weapon::Info_Flags::Huge] ) {
if ( lep->type != OBJ_SHIP ) {
tentative_return = true;
continue;
}
if ( !(Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge()) ) {
tentative_return = true;
continue;
if ( wip->wi_flags[Weapon::Info_Flags::Small_only] ) {
if ( (lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge()) ) {
continue;
}
}
bool tagged_only = ((wip->wi_flags[Weapon::Info_Flags::Tagged_only]) || (ss->weapons.flags[Ship::Weapon_Flags::Tagged_Only]));
if (lep->type == OBJ_SHIP) {
// Check if we're targeting a protected ship
if (lep->flags[Object::Object_Flags::Protected]) {
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
continue;
}
// Check if we're targeting a beam protected ship with a beam weapon
if ( (lep->flags[Object::Object_Flags::Beam_protected]) && (wip->wi_flags[Weapon::Info_Flags::Beam]) ) {
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
continue;
}
// Check if we're targeting a flak protected ship with a flak weapon
else if ( (lep->flags[Object::Object_Flags::Flak_protected]) && (wip->wi_flags[Weapon::Info_Flags::Flak]) ) {
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
continue;
}
// Check if we're targeting a laser protected ship with a laser weapon
else if ( (lep->flags[Object::Object_Flags::Laser_protected]) && (wip->subtype == WP_LASER) ) {
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
continue;
}
// Check if we're targeting a missile protected ship with a missile weapon
else if ( (lep->flags[Object::Object_Flags::Missile_protected]) && (wip->subtype == WP_MISSILE) ) {
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
continue;
}
// Check if weapon or turret is set to tagged-only
// must check here in case turret has multiple weapons and not all are tagged-only
else if (!ship_is_tagged(lep) && tagged_only) {
continue;
}
}
else
{
// check tagged-only for non-ship targets
if (tagged_only && (!(lep->type == OBJ_WEAPON) || (The_mission.ai_profile->flags[AI::Profile_Flags::Strict_turred_tagged_only_targeting]))) {
continue;
}
}
//Add it to the list
valid_weapons[num_valid++] = i;
}
}
// Similar check for small weapons
if ( wip->wi_flags[Weapon::Info_Flags::Small_only] ) {
if ( (lep->type == OBJ_SHIP) && Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge() ) {
tentative_return = true;
continue;
}
}
bool tagged_only = ((wip->wi_flags[Weapon::Info_Flags::Tagged_only]) || (ss->weapons.flags[Ship::Weapon_Flags::Tagged_Only]));
// If targeting protected or beam protected ship, don't fire. Reset enemy objnum
// (note: due to the loop, we need to check all weapons on this turret. if none of them are valid, that's when the enemy objnum is reset)
if (lep->type == OBJ_SHIP) {
// Check if we're targeting a protected ship
if (lep->flags[Object::Object_Flags::Protected]) {
// *none* of the weapons will work on this ship, so just quit the loop
tentative_return = true;
break;
}
// Check if we're targeting a beam protected ship with a beam weapon
if ( (lep->flags[Object::Object_Flags::Beam_protected]) && (wip->wi_flags[Weapon::Info_Flags::Beam]) ) {
tentative_return = true;
continue;
}
// Check if we're targeting a flak protected ship with a flak weapon
else if ( (lep->flags[Object::Object_Flags::Flak_protected]) && (wip->wi_flags[Weapon::Info_Flags::Flak]) ) {
tentative_return = true;
continue;
}
// Check if we're targeting a laser protected ship with a laser weapon
else if ( (lep->flags[Object::Object_Flags::Laser_protected]) && (wip->subtype == WP_LASER) ) {
tentative_return = true;
continue;
}
// Check if we're targeting a missile protected ship with a missile weapon
else if ( (lep->flags[Object::Object_Flags::Missile_protected]) && (wip->subtype == WP_MISSILE) ) {
tentative_return = true;
continue;
}
// Check if weapon or turret is set to tagged-only
// must check here in case turret has multiple weapons and not all are tagged-only
else if (tagged_only && !ship_is_tagged(lep)) {
tentative_return = true;
continue;
}
}
else {
// check tagged-only for bombs only if the flag is set; see Mantis #3114
if (tagged_only && ((lep->type != OBJ_WEAPON) || The_mission.ai_profile->flags[AI::Profile_Flags::Strict_turret_tagged_only_targeting])) {
tentative_return = true;
continue;
}
}
// If we made it this far, we have a valid weapon to fire
valid_weapons[num_valid++] = i;
}
// in the original code, spawning weapons immediately bailed after firing,
// so bail unless we have other weapons that need the rest of the function
if (!we_did_non_spawning_logic)
return;
//none of our guns can hit the enemy, so find a new enemy
if (num_valid == 0) {
//none of our guns can hit the enemy, so find a new one
if(num_valid < 1)
ss->turret_enemy_objnum = -1;
ss->turret_time_enemy_in_range = 0.0f;
// in the original code, we returned where the "tentative return" variable was set,
// so return for real now, since we don't have a reason to remain in the function
if (tentative_return)
return;
}
// Maybe pick a new enemy, unless targeting has been taken over by scripting
if ( turret_should_pick_new_target(ss) && !ss->scripting_target_override ) {
Num_find_turret_enemy++;
int objnum = find_turret_enemy(ss, parent_objnum, &gpos, &gvec, ss->turret_enemy_objnum);
//Assert(objnum < 0 || is_target_beam_valid(tp, objnum));
if (objnum >= 0) {
if (objnum >= 0 && is_target_beam_valid(&ss->weapons, &Objects[objnum])) {
if (ss->turret_enemy_objnum == -1) {
ss->turret_enemy_objnum = objnum;
ss->targeted_subsys = NULL; // Turret has retargeted; reset subsystem - Valathil for Mantis #2652
@@ -2527,17 +2529,24 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
return;
}
if ( lep == nullptr ){
if ( lep == NULL ){
mprintf(("last enemy is null\n"));
return;
}
//This can't happen. See above code
//Assert(ss->turret_enemy_objnum != -1);
bool in_fov = turret_fov_test(ss, &gvec, &v2e);
bool something_was_ok_to_fire = false;
float dot;
bool in_fov;
in_fov = turret_fov_test(ss, &gvec, &v2e);
if (in_fov) {
// Ok, the turret is lined up... now line up a particular gun.
bool ok_to_fire = false;
bool something_was_ok_to_fire=false;
vec3d tv2e; //so flak can get their jitter without screwing up other guns
if (in_fov ) {
// Do salvo thing separately - to prevent messing up things
int number_of_firings;
@@ -2551,47 +2560,59 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
number_of_firings = num_valid;
}
for (int i = 0; i < number_of_firings; ++i)
for(i = 0; i < number_of_firings; i++)
{
int valid_index;
if (tp->flags[Model::Subsystem_Flags::Turret_salvo])
valid_index = 0;
else
valid_index = i;
auto wip = get_turret_weapon_wip(&ss->weapons, valid_weapons[valid_index]);
// Forces the firing turret to retain the firingpoints of their weapons:
// if the turret has multiple banks, the first bank will only fire from the first firepoint,
// the second bank only from the second firepoint, and so on.
if (tp->flags[Model::Subsystem_Flags::Turret_fixed_fp])
{
int ffp_bank = valid_weapons[valid_index];
int ffp_pos = 0;
int ffp_bank;
ffp_bank = valid_weapons[i];
if (ffp_bank < MAX_SHIP_PRIMARY_BANKS)
ss->turret_next_fire_pos = ffp_bank;
{
ffp_pos = ffp_bank;
}
else
ss->turret_next_fire_pos = ffp_bank - MAX_SHIP_PRIMARY_BANKS + ss->weapons.num_primary_banks;
{
ffp_pos = ffp_bank - MAX_SHIP_PRIMARY_BANKS + ss->weapons.num_primary_banks;
}
ss->turret_next_fire_pos = ffp_pos;
}
// Ok, the turret is lined up... now line up a particular gun.
bool ok_to_fire = false;
ship_get_global_turret_gun_info(&Objects[parent_objnum], ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
// Fire in the direction the turret is facing, not right at the target regardless of turret dir.
vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
dist_to_enemy = vm_vec_normalize(&v2e);
dot = vm_vec_dot(&v2e, &gvec);
if (tp->flags[Model::Subsystem_Flags::Turret_salvo])
wip = get_turret_weapon_wip(&ss->weapons, valid_weapons[0]);
else
wip = get_turret_weapon_wip(&ss->weapons, valid_weapons[i]);
// We're ready to fire... now get down to specifics, like where is the
// actual gun point and normal, not just the one for whole turret.
ship_get_global_turret_gun_info(objp, ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
// Fire in the direction the turret is facing, not right at the target regardless of turret dir.
// [Yet this retail comment precedes the calculation of vector-to-enemy...]
vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
dist_to_enemy = vm_vec_normalize(&v2e);
float dot = vm_vec_dot(&v2e, &gvec);
// (flak jitter moved to after we obtain shoot_vector below)
// moved here as if there are two weapons with indentical fire stamps
// they would have shared the fire point.
tv2e = gvec;
// make sure to reset this for current weapon
ok_to_fire = false;
// if the weapon is a flak gun, add some jitter to its aim so it fires in a "cone"
// to make a cool visual effect and make them less lethal
if(wip->wi_flags[Weapon::Info_Flags::Flak]){
flak_jitter_aim(&tv2e, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS), wip);
}
// Fire if:
// dumbfire and nearly pointing at target.
// heat seeking and target in a fairly wide cone.
// aspect seeking and target is locked.
//turret_weapon_class = tp->turret_weapon_type;
bool in_sight = false;
if (The_mission.ai_profile->flags[AI::Profile_Flags::Use_only_single_fov_for_turrets]) {
@@ -2609,7 +2630,6 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
}
}
// if dumbfire (lasers and non-homing missiles)
if ( !(wip->is_homing()) )
{
if ((dist_to_enemy < 75.0f) || in_sight)
@@ -2618,18 +2638,16 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
ok_to_fire = true;
}
}
// if heat seekers
else if ( wip->wi_flags[Weapon::Info_Flags::Homing_heat] )
{
{ // if heat seekers
if ((dist_to_enemy < 50.0f) || in_sight)
{
turret_update_enemy_in_range(ss, 2*wip->fire_wait);
ok_to_fire = true;
}
}
// if aspect seeker
else if ( wip->wi_flags[Weapon::Info_Flags::Homing_aspect] )
{
{ // if aspect seeker
if ((dist_to_enemy < 50.0f) || in_sight)
{
turret_update_enemy_in_range(ss, 2*wip->fire_wait);
@@ -2639,9 +2657,8 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
ok_to_fire = true;
}
}
// if javelin heat seeker
else if ( wip->wi_flags[Weapon::Info_Flags::Homing_javelin] )
{
{ // if javelin heat seeker
if ((dist_to_enemy < 50.0f) || in_sight)
{
turret_update_enemy_in_range(ss, 2*wip->fire_wait);
@@ -2655,7 +2672,6 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
}
}
// maybe check that the gun vector doesn't intersect with the hull
if ( ok_to_fire && (tp->flags[Model::Subsystem_Flags::Turret_hull_check]) ) {
int model_num = Ship_info[shipp->ship_info_index].model_num;
vec3d end;
@@ -2680,8 +2696,8 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
{
// starting animation checks
if (ss->turret_animation_position == MA_POS_NOT_SET) {
if ( model_anim_start_type(shipp, AnimationTriggerType::TurretFiring, ss->system_info->subobj_num, 1) ) {
ss->turret_animation_done_time = model_anim_get_time_type(shipp, AnimationTriggerType::TurretFiring, ss->system_info->subobj_num);
if ( model_anim_start_type(shipp, TRIGGER_TYPE_TURRET_FIRING, ss->system_info->subobj_num, 1) ) {
ss->turret_animation_done_time = model_anim_get_time_type(shipp, TRIGGER_TYPE_TURRET_FIRING, ss->system_info->subobj_num);
ss->turret_animation_position = MA_POS_SET;
}
}
@@ -2695,45 +2711,32 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
if ( ok_to_fire )
{
// finally!
something_was_ok_to_fire = true;
Num_turrets_fired++;
// (Despite the retail comment above, retail actually fired toward the enemy; v2e = vector-to-enemy)
vec3d shoot_vector = v2e;
if (tp->flags[Model::Subsystem_Flags::Fire_on_normal])
shoot_vector = gvec;
// if the weapon is a flak gun, add some jitter to its aim so it fires in a "cone"
// to make a cool visual effect and make them less lethal
if (wip->wi_flags[Weapon::Info_Flags::Flak]) {
flak_jitter_aim(&shoot_vector, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS), wip);
}
turret_fire_weapon(valid_weapons[valid_index], ss, parent_objnum, &gpos, &shoot_vector, &predicted_enemy_pos);
}
else
{
turret_update_enemy_in_range(ss, -4*wip->fire_wait);
if (tp->flags[Model::Subsystem_Flags::Use_multiple_guns])
set_turret_weapon_next_fire_stamp(swp, valid_weapons[valid_index], 500);
//Pass along which gun we are using
if (tp->flags[Model::Subsystem_Flags::Turret_salvo])
turret_fire_weapon(valid_weapons[0], ss, parent_objnum, &gpos, &tv2e, &predicted_enemy_pos);
else
ss->turret_next_fire_stamp = timestamp(500);
turret_fire_weapon(valid_weapons[i], ss, parent_objnum, &gpos, &tv2e, &predicted_enemy_pos);
} else {
// make sure salvo fire mode does not turn into autofire
if ((tp->flags[Model::Subsystem_Flags::Turret_salvo]) && ((i + 1) == number_of_firings)) {
ai_info *parent_aip = &Ai_info[shipp->ai_index];
turret_set_next_fire_timestamp(valid_weapons[valid_index], wip, ss, parent_aip);
ai_info *parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
turret_set_next_fire_timestamp(valid_weapons[0], wip, ss, parent_aip);
}
}
// we are done firing, so fire the next weapon from the next firing point
// (This was originally done under the "We're ready to fire..." comment)
ss->turret_next_fire_pos++;
}
if (!something_was_ok_to_fire)
if(!something_was_ok_to_fire)
{
if (ss->turret_best_weapon >= 0) {
//Impose a penalty on turret accuracy for losing site of its goal, or just not being able to fire.
turret_update_enemy_in_range(ss, -4*Weapon_info[ss->turret_best_weapon].fire_wait);
}
ss->turret_next_fire_stamp = timestamp(500);
// If nothing is OK to fire (lost track of the target?)
// reset the target (so we don't continue to track what we can't hit)
if (tp->flags[Model::Subsystem_Flags::Turret_only_target_if_can_fire])
@@ -2744,31 +2747,37 @@ void ai_fire_from_turret(ship *shipp, ship_subsys *ss)
}
else
{
//something did fire, get the lowest valid timestamp
// don't do this if we already set a turret timestamp previously in the function
if (timestamp_until(ss->turret_next_fire_stamp) <= 0)
ss->turret_next_fire_stamp = INT_MAX;
//something did fire, get the lowest valid timestamp
for (i = 0; i < MAX_SHIP_WEAPONS; i++)
{
int minimum_stamp = -1;
for (int i = 0; i < MAX_SHIP_WEAPONS; ++i)
if (i < MAX_SHIP_PRIMARY_BANKS)
{
int stamp = (i < MAX_SHIP_PRIMARY_BANKS) ? swp->next_primary_fire_stamp[i] : swp->next_secondary_fire_stamp[i - MAX_SHIP_PRIMARY_BANKS];
//timestamp range is 2 to INT_MAX/2
if (swp->next_primary_fire_stamp[i] < 2) continue;
if (swp->next_primary_fire_stamp[i] < ss->turret_next_fire_stamp)
{
ss->turret_next_fire_stamp = swp->next_primary_fire_stamp[i];
}
}
else
{
//timestamp range is 2 to INT_MAX/2
if (swp->next_secondary_fire_stamp[i - MAX_SHIP_PRIMARY_BANKS] < 2) continue;
// valid timestamps start at 2; stamp must be in the future
if (stamp < 2 || timestamp_until(stamp) <= 0)
continue;
if (swp->next_secondary_fire_stamp[i - MAX_SHIP_PRIMARY_BANKS] < ss->turret_next_fire_stamp)
{
ss->turret_next_fire_stamp = swp->next_secondary_fire_stamp[i - MAX_SHIP_PRIMARY_BANKS];
}
// find minimum
if (minimum_stamp < 0 || timestamp_until(stamp) < timestamp_until(minimum_stamp))
minimum_stamp = stamp;
}
// set turret timestamp, or 100ms for sanity's sake
if (minimum_stamp >= 0)
ss->turret_next_fire_stamp = minimum_stamp;
else
ss->turret_next_fire_stamp = timestamp(100);
}
// Wanderer -- sanity check
// if timestamp is still at int_max reset the wait to 100 ms instead of locking the turret for the rest of the game
if (ss->turret_next_fire_stamp == INT_MAX)
ss->turret_next_fire_stamp = timestamp(100);
}
}
else
+14 -28
View File
@@ -151,21 +151,14 @@ int unpack_pixel(anim_instance *ai, ubyte *data, ubyte pix, int aabitmap, int bp
bit_16 = (ushort)pix;
break;
case 8:
// 8 bit-per-pixel aa bitmaps are a bit special since they only use a palette index value in the range [0, 15]. These
// palette indexes must be remapped to alpha values between [0, 255] which is what graphics code expects. Palette
// range [0, 14] is a gradient from black to white, and palette index 15 is a special color which indicates the background
// area of a HUD gauge. Retail code uses the final alpha value for index 1 for this special index to give gauges a dark
// transparent background.
if (pix > 15) {
bit_8 = 255;
// 8 bit-per-pixel aa bitmaps are a bit special since they only use value in the range [0, 15] where 15 wraps
// around back to 0. Since the rest of the code expects the value to be in the range [0, 255] the pixel value
// needs to be adjusted here. By muliplying the value with 17 the original range [0, 15] is mapped to [0, 255]
if (pix >= 15) {
bit_8 = 0;
} else {
bit_8 = (ubyte)(pix * 17);
}
else if (pix == 15) {
bit_8 = 18;
}
else {
bit_8 = (ubyte)(pix * 18);
}
break;
default:
Int3();
@@ -249,21 +242,14 @@ int unpack_pixel_count(anim_instance *ai, ubyte *data, ubyte pix, int count = 0,
bit_16 = (ushort)pix;
break;
case 8 :
// 8 bit-per-pixel aa bitmaps are a bit special since they only use a palette index value in the range [0, 15]. These
// palette indexes must be remapped to alpha values between [0, 255] which is what graphics code expects. Palette
// range [0, 14] is a gradient from black to white, and palette index 15 is a special color which indicates the background
// area of a HUD gauge. Retail code uses the final alpha value for index 1 for this special index to give gauges a dark
// transparent background.
if (pix > 15) {
bit_8 = 255;
// 8 bit-per-pixel aa bitmaps are a bit special since they only use value in the range [0, 15] where 15 wraps
// around back to 0. Since the rest of the code expects the value to be in the range [0, 255] the pixel value
// needs to be adjusted here. By muliplying the value with 17 the original range [0, 15] is mapped to [0, 255]
if (pix >= 15) {
bit_8 = 0;
} else {
bit_8 = (ubyte)(pix * 17);
}
else if (pix == 15) {
bit_8 = 18;
}
else {
bit_8 = (ubyte)(pix * 18);
}
break;
default :
Int3();
+27 -47
View File
@@ -36,7 +36,6 @@
#include "particle/particle.h"
#include "render/3d.h"
#include "ship/ship.h"
#include "ship/shipfx.h"
#include "ship/shiphit.h"
#include "species_defs/species_defs.h"
#include "stats/scoring.h"
@@ -929,6 +928,7 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
Assert( other_obj->type == OBJ_WEAPON );
mc.model_instance_num = Asteroids[num].model_instance_num;
mc.model_num = Asteroid_info[Asteroids[num].asteroid_type].model_num[asteroid_subtype]; // Fill in the model to check
model_clear_instance( mc.model_num );
mc.orient = &pasteroid->orient; // The object's orient
mc.pos = &pasteroid->pos; // The object's position
mc.p0 = &other_obj->last_pos; // Point 1 of ray to check
@@ -942,11 +942,7 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
if (hitnormal)
{
vec3d normal;
if (mc.model_instance_num >= 0)
model_instance_find_world_dir(&normal, &mc.hit_normal, mc.model_instance_num, mc.hit_submodel, mc.orient);
else
model_find_world_dir(&normal, &mc.hit_normal, mc.model_num, mc.hit_submodel, mc.orient);
model_find_world_dir(&normal, &mc.hit_normal, mc.model_num, mc.hit_submodel, mc.orient);
*hitnormal = normal;
}
@@ -1014,51 +1010,51 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
// first test against the sphere - if this fails then don't do any submodel tests
mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
SCP_vector<int> submodel_vector;
polymodel_instance *pmi;
if (model_collide(&mc)) {
// Set earliest hit time
asteroid_hit_info->hit_time = FLT_MAX;
auto pmi = model_get_instance(Ships[heavy_obj->instance].model_instance_num);
auto pm = model_get(pmi->model_num);
// Do collision the cool new way
if ( asteroid_hit_info->collide_rotate ) {
// We collide with the sphere, find the list of rotating submodels and test one at a time
SCP_vector<int> submodel_vector;
model_get_rotating_submodel_list(&submodel_vector, heavy_obj);
// turn off all rotating submodels, collide against only 1 at a time.
// turn off collision detection for all rotating submodels
for (auto submodel: submodel_vector) {
pmi->submodel[submodel].collision_checked = true;
// Get polymodel and turn off all rotating submodels, collide against only 1 at a time.
pmi = model_get_instance(Ships[heavy_obj->instance].model_instance_num);
// turn off all rotating submodels and test for collision
for (size_t j=0; j<submodel_vector.size(); j++) {
pmi->submodel[submodel_vector[j]].collision_checked = true;
}
// reset flags to check MC_CHECK_MODEL | MC_CHECK_SPHERELINE and maybe MC_CHECK_INVISIBLE_FACES and MC_SUBMODEL_INSTANCE
mc.flags = copy_flags | MC_SUBMODEL_INSTANCE;
// check each submodel in turn
for (auto submodel: submodel_vector) {
auto smi = &pmi->submodel[submodel];
// turn on just one submodel for collision test
smi->collision_checked = false;
// check each submodel in turn
for (size_t i=0; i<submodel_vector.size(); i++) {
// turn on submodel for collision test
pmi->submodel[submodel_vector[i]].collision_checked = false;
// set angles for last frame (need to set to prev to get p0)
angles copy_angles = smi->angs;
angles copy_angles = pmi->submodel[submodel_vector[i]].angs;
// find the start and end positions of the sphere in submodel RF
smi->angs = smi->prev_angs;
world_find_model_instance_point(&p0, &light_obj->last_pos, pm, pmi, submodel, &heavy_obj->last_orient, &heavy_obj->last_pos);
pmi->submodel[submodel_vector[i]].angs = pmi->submodel[submodel_vector[i]].prev_angs;
world_find_model_instance_point(&p0, &light_obj->last_pos, pmi, submodel_vector[i], &heavy_obj->last_orient, &heavy_obj->last_pos);
smi->angs = copy_angles;
world_find_model_instance_point(&p1, &light_obj->pos, pm, pmi, submodel, &heavy_obj->orient, &heavy_obj->pos);
pmi->submodel[submodel_vector[i]].angs = copy_angles;
world_find_model_instance_point(&p1, &light_obj->pos, pmi, submodel_vector[i], &heavy_obj->orient, &heavy_obj->pos);
mc.p0 = &p0;
mc.p1 = &p1;
mc.orient = &vmd_identity_matrix;
mc.submodel_num = submodel;
mc.submodel_num = submodel_vector[i];
if ( model_collide(&mc) ) {
if ( mc.hit_dist < asteroid_hit_info->hit_time ) {
@@ -1069,23 +1065,23 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
// set up asteroid_hit_info for rotating submodel
if (asteroid_hit_info->edge_hit == 0) {
model_instance_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, pm, pmi, mc.hit_submodel, &heavy_obj->orient);
model_instance_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, Ships[heavy_obj->instance].model_instance_num, mc.hit_submodel, &heavy_obj->orient);
}
// find position in submodel RF of light object at collison
vec3d int_light_pos, diff;
vm_vec_sub(&diff, mc.p1, mc.p0);
vm_vec_scale_add(&int_light_pos, mc.p0, &diff, mc.hit_dist);
model_instance_find_world_point(&asteroid_hit_info->light_collision_cm_pos, &int_light_pos, pm, pmi, mc.hit_submodel, &heavy_obj->orient, &zero);
model_instance_find_world_point(&asteroid_hit_info->light_collision_cm_pos, &int_light_pos, mc.model_instance_num, mc.hit_submodel, &heavy_obj->orient, &zero);
}
}
// Don't look at this submodel again
smi->collision_checked = true;
pmi->submodel[submodel_vector[i]].collision_checked = true;
}
}
// Now complete base model collision checks that do not take into account rotating submodels.
// Recover and do usual ship_ship collision, but without rotating submodels
mc.flags = copy_flags;
*mc.p0 = copy_p0;
*mc.p1 = copy_p1;
@@ -1101,7 +1097,7 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
// get collision normal if not edge hit
if (asteroid_hit_info->edge_hit == 0) {
model_instance_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, pm, pmi, mc.hit_submodel, &heavy_obj->orient);
model_instance_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, Ships[heavy_obj->instance].model_instance_num, mc.hit_submodel, &heavy_obj->orient);
}
// find position in submodel RF of light object at collison
@@ -1117,6 +1113,7 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
// Asteroid is heavier obj
mc.model_instance_num = Asteroids[num].model_instance_num;
mc.model_num = Asteroid_info[Asteroids[num].asteroid_type].model_num[asteroid_subtype]; // Fill in the model to check
model_clear_instance( mc.model_num );
mc.orient = &pasteroid->orient; // The object's orient
mc.radius = model_get_core_radius(Ship_info[Ships[pship_obj->instance].ship_info_index].model_num);
@@ -1140,23 +1137,6 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
}
}
// check if the hit point is beyond the clip plane if the ship is warping.
if (mc_ret_val) {
WarpEffect* warp_effect = nullptr;
ship* shipp = &Ships[pship_obj->instance];
// this is extremely confusing but mc.hit_point_world isn't actually in world coords
// everything above was calculated relative to the heavy's position
vec3d actual_world_hit_pos = mc.hit_point_world + heavy_obj->pos;
if ((shipp->is_arriving()) && (shipp->warpin_effect != nullptr))
warp_effect = shipp->warpin_effect;
else if ((shipp->flags[Ship::Ship_Flags::Depart_warp]) && (shipp->warpout_effect != nullptr))
warp_effect = shipp->warpout_effect;
if (warp_effect != nullptr && point_is_clipped_by_warp(&actual_world_hit_pos, warp_effect))
mc_ret_val = 0;
}
if ( mc_ret_val ) {
+26 -26
View File
@@ -108,7 +108,7 @@ bool Sel_NextNav()
// ********************************************************************************************
const vec3d *NavPoint::GetPosition()
vec3d *NavPoint::GetPosition()
{
if (flags & NP_WAYPOINT)
{
@@ -123,7 +123,7 @@ const vec3d *NavPoint::GetPosition()
}
// ********************************************************************************************
bool CanAutopilot(const vec3d *targetPos, bool send_msg)
bool CanAutopilot(vec3d targetPos, bool send_msg)
{
if (CurrentNav == -1)
{
@@ -140,7 +140,7 @@ bool CanAutopilot(const vec3d *targetPos, bool send_msg)
}
// You cannot autopilot if you're within 1000 meters of your destination nav point
if (vm_vec_dist_quick(targetPos, Navs[CurrentNav].GetPosition()) < 1000) {
if (vm_vec_dist_quick(&targetPos, Navs[CurrentNav].GetPosition()) < 1000) {
if (send_msg)
send_autopilot_msgID(NP_MSG_FAIL_TOCLOSE);
return false;
@@ -156,7 +156,7 @@ bool CanAutopilot(const vec3d *targetPos, bool send_msg)
&& !(Ship_info[Ships[other_objp->instance].ship_info_index].flags[Ship::Info_Flags::Cargo])) // ignore cargo
{
// Cannot autopilot if enemy within AutopilotMinEnemyDistance meters
if (vm_vec_dist_quick(targetPos, &other_objp->pos) < AutopilotMinEnemyDistance) {
if (vm_vec_dist_quick(&targetPos, &other_objp->pos) < AutopilotMinEnemyDistance) {
if (send_msg)
send_autopilot_msgID(NP_MSG_FAIL_HOSTILES);
return false;
@@ -173,7 +173,7 @@ bool CanAutopilot(const vec3d *targetPos, bool send_msg)
if (Asteroids[n].flags & AF_USED)
{
// Cannot autopilot if asteroid within AutopilotMinAsteroidDistance meters
if (vm_vec_dist_quick(targetPos, &Objects[Asteroids[n].objnum].pos) < AutopilotMinAsteroidDistance) {
if (vm_vec_dist_quick(&targetPos, &Objects[Asteroids[n].objnum].pos) < AutopilotMinAsteroidDistance) {
if (send_msg)
send_autopilot_msgID(NP_MSG_FAIL_HAZARD);
return false;
@@ -409,11 +409,11 @@ bool StartAutopilot()
if (leader_objp != &Objects[Ships[i].objnum])
{
// not leader.. get our position relative to leader
get_absolute_wing_pos(&goal_point, leader_objp, wingnum, wing_index, aip->ai_flags[AI::AI_Flags::Formation_object], true);
get_absolute_wing_pos_autopilot(&goal_point, leader_objp, wing_index, aip->ai_flags[AI::AI_Flags::Formation_object]);
}
else
{
ai_clear_wing_goals(&Wings[wingnum]);
ai_clear_wing_goals(wingnum);
j = 1+int( (float)floor(double(wcount-1)/2.0) );
switch (wcount % 2)
{
@@ -484,7 +484,7 @@ bool StartAutopilot()
//ai_add_wing_goal_player( AIG_TYPE_PLAYER_WING, AI_GOAL_WAYPOINTS_ONCE, 0, target_shipname, wingnum );
//ai_clear_ship_goals( &(Ai_info[Ships[num].ai_index]) );
ai_clear_wing_goals( &Wings[i] );
ai_clear_wing_goals( i );
if (Navs[CurrentNav].flags & NP_WAYPOINT)
{
@@ -989,7 +989,7 @@ void nav_warp(bool prewarp=false)
/* using the vector of the flight leaders's path, simulate moving the
flight along this path by checking the autopilot conditions as specific
intervals along the path*/
while (CanAutopilot(&tpos))
while (CanAutopilot(tpos))
{
vm_vec_add(&tpos, &tpos, &pos);
}
@@ -1192,7 +1192,7 @@ void send_autopilot_msgID(int msgid)
}
// ********************************************************************************************
void send_autopilot_msg(const char *msg, const char *snd)
void send_autopilot_msg(char *msg, char *snd)
{
// setup
if (audio_handle != -1)
@@ -1312,7 +1312,7 @@ void parse_autopilot_table(const char *filename)
// ********************************************************************************************
// Finds a Nav point by name
int FindNav(const char *Nav)
int FindNav(char *Nav)
{
for (int i = 0; i < MAX_NAVPOINTS; i++)
{
@@ -1325,7 +1325,7 @@ int FindNav(const char *Nav)
// ********************************************************************************************
// Removes a Nav
bool DelNavPoint(const char *Nav)
bool DelNavPoint(char *Nav)
{
int n = FindNav(Nav);
@@ -1354,7 +1354,7 @@ bool DelNavPoint(int nav)
// ********************************************************************************************
// adds a Nav
bool AddNav_Ship(const char *Nav, const char *TargetName, int flags)
bool AddNav_Ship(char *Nav, char *TargetName, int flags)
{
// find an empty nav - should be the end
@@ -1397,7 +1397,7 @@ bool AddNav_Ship(const char *Nav, const char *TargetName, int flags)
}
bool AddNav_Waypoint(const char *Nav, const char *WP_Path, int node, int flags)
bool AddNav_Waypoint(char *Nav, char *WP_Path, int node, int flags)
{
// find an empty nav - should be the end
@@ -1435,7 +1435,7 @@ bool AddNav_Waypoint(const char *Nav, const char *WP_Path, int node, int flags)
// ********************************************************************************************
//Get Flags
int Nav_Get_Flags(const char *Nav)
int Nav_Get_Flags(char *Nav)
{
int flags = 0;
@@ -1451,7 +1451,7 @@ int Nav_Get_Flags(const char *Nav)
// Sexp Accessors
//Generic
bool Nav_Set_Flag(const char *Nav, int flag)
bool Nav_Set_Flag(char *Nav, int flag)
{
Assert(!(flag & NP_VALIDTYPE));
int nav = FindNav(Nav);
@@ -1467,7 +1467,7 @@ bool Nav_Set_Flag(const char *Nav, int flag)
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_UnSet_Flag(const char *Nav, int flag)
bool Nav_UnSet_Flag(char *Nav, int flag)
{
Assert(!(flag & NP_VALIDTYPE));
@@ -1484,7 +1484,7 @@ bool Nav_UnSet_Flag(const char *Nav, int flag)
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//Named
bool Nav_Set_Hidden(const char *Nav)
bool Nav_Set_Hidden(char *Nav)
{
return Nav_Set_Flag(Nav, NP_HIDDEN);
@@ -1492,14 +1492,14 @@ bool Nav_Set_Hidden(const char *Nav)
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_Set_NoAccess(const char *Nav)
bool Nav_Set_NoAccess(char *Nav)
{
return Nav_Set_Flag(Nav, NP_NOACCESS);
}
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_Set_Visited(const char *Nav)
bool Nav_Set_Visited(char *Nav)
{
return Nav_Set_Flag(Nav, NP_VISITED);
@@ -1507,28 +1507,28 @@ bool Nav_Set_Visited(const char *Nav)
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_UnSet_Hidden(const char *Nav)
bool Nav_UnSet_Hidden(char *Nav)
{
return Nav_UnSet_Flag(Nav, NP_HIDDEN);
}
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_UnSet_NoAccess(const char *Nav)
bool Nav_UnSet_NoAccess(char *Nav)
{
return Nav_UnSet_Flag(Nav, NP_NOACCESS);
}
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool Nav_UnSet_Visited(const char *Nav)
bool Nav_UnSet_Visited(char *Nav)
{
return Nav_UnSet_Flag(Nav, NP_VISITED);
}
// ********************************************************************************************
// Selects a navpoint by name.
void SelectNav(const char *Nav)
void SelectNav(char *Nav)
{
for (int i = 0; i < MAX_NAVPOINTS; i++)
{
@@ -1547,7 +1547,7 @@ void DeselectNav()
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
unsigned int DistanceTo(const char *nav)
unsigned int DistanceTo(char *nav)
{
int n = FindNav(nav);
@@ -1564,7 +1564,7 @@ unsigned int DistanceTo(int nav)
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
bool IsVisited(const char *nav)
bool IsVisited(char *nav)
{
int n = FindNav(nav);
+21 -21
View File
@@ -32,17 +32,17 @@ public:
char m_NavName[32];
int flags;
const void *target_obj;
void *target_obj;
int waypoint_num; //only used when flags & NP_WAYPOINT
const vec3d *GetPosition();
vec3d *GetPosition();
void clear()
{
m_NavName[0] = 0;
flags = 0;
target_obj = nullptr;
target_obj = NULL;
waypoint_num = -1;
}
};
@@ -82,11 +82,11 @@ bool Sel_NextNav();
// * No asteroids within AutopilotMinAsteroidDistance meters
// * Destination > 1,000 meters away
// * Support ship not present or is actively leaving
bool CanAutopilot(const vec3d *targetPos, bool send_msg=false);
bool CanAutopilot(vec3d targetPos, bool send_msg=false);
// Check if autopilot is allowed at player's current position
// See CanAutopilot(vec3d, bool) for more information
inline bool CanAutopilot(bool send_msg=false) { return CanAutopilot(&Player_obj->pos, send_msg); }
inline bool CanAutopilot(bool send_msg=false) { return CanAutopilot(Player_obj->pos, send_msg); }
// Engages autopilot
// This does:
@@ -120,42 +120,42 @@ void NavSystem_Init();
void parse_autopilot_table(const char *filename);
// Finds a Nav point by name
int FindNav(const char *Nav);
int FindNav(char *Nav);
// Selects a Nav point by name
void SelectNav(const char *Nav);
void SelectNav(char *Nav);
// Deselects any navpoint selected.
void DeselectNav();
// Removes a Nav
bool DelNavPoint(const char *Nav);
bool DelNavPoint(char *Nav);
bool DelNavPoint(int nav);
// adds a Nav
bool AddNav_Ship(const char *Nav, const char *TargetName, int flags);
bool AddNav_Waypoint(const char *Nav, const char *WP_Path, int node, int flags);
bool AddNav_Ship(char *Nav, char *TargetName, int flags);
bool AddNav_Waypoint(char *Nav, char *WP_Path, int node, int flags);
// Sexp Accessors
bool Nav_Set_Flag(const char *Nav, int flag);
bool Nav_UnSet_Flag(const char *Nav, int flag);
bool Nav_Set_Flag(char *Nav, int flag);
bool Nav_UnSet_Flag(char *Nav, int flag);
bool Nav_Set_Hidden(const char *Nav);
bool Nav_Set_NoAccess(const char *Nav);
bool Nav_Set_Visited(const char *Nav);
bool Nav_Set_Hidden(char *Nav);
bool Nav_Set_NoAccess(char *Nav);
bool Nav_Set_Visited(char *Nav);
bool Nav_UnSet_Hidden(const char *Nav);
bool Nav_UnSet_NoAccess(const char *Nav);
bool Nav_UnSet_Visited(const char *Nav);
bool Nav_UnSet_Hidden(char *Nav);
bool Nav_UnSet_NoAccess(char *Nav);
bool Nav_UnSet_Visited(char *Nav);
// Useful functions
unsigned int DistanceTo(const char *nav);
unsigned int DistanceTo(char *nav);
unsigned int DistanceTo(int nav);
bool IsVisited(const char *nav);
bool IsVisited(char *nav);
bool IsVisited(int nav);
void send_autopilot_msg(const char *msg, const char *snd=nullptr);
void send_autopilot_msg(char *msg, char *snd=NULL);
void send_autopilot_msgID(int msgid);
#endif
+22 -10
View File
@@ -9,6 +9,18 @@
*
*/
/**
* @file bm_internal.h
* These are functions and types used by bmpman and a few others.
*
* @details It is a "protected" header that requires BMPMAN_INTERNAL to be defined before it can be included. This is to
* provide a small measure of safety since this functions can cause problems if not used correctly
*/
#ifndef BMPMAN_INTERNAL
#error The file header "bmpman/bm_internal.h" is protected. Make sure you know what you are doing!
#endif
#include "bmpman/bmpman.h"
#include <array>
@@ -46,7 +58,7 @@ union bm_extra_info {
// Stuff needed for user bitmaps
void* data; //!< For user bitmaps, this is where the data comes from
ubyte bpp; //!< For user bitmaps, this is what format the data is
ushort flags; //!< For user bitmaps, Flags passed to bm_create
ubyte flags; //!< For user bitmaps, Flags passed to bm_create
} user;
};
@@ -70,7 +82,7 @@ struct bitmap_entry {
// Stuff to keep track of usage
ubyte preloaded; //!< If set, then this was loaded from the lst file
int preload_count; //!< how many times this gets used in game, for unlocking
ushort used_flags; //!< What flags it was accessed thru
ubyte used_flags; //!< What flags it was accessed thru
int load_count;
bitmap bm; //!< Bitmap info
@@ -93,14 +105,14 @@ struct bitmap_slot {
};
// image specific lock functions
void bm_lock_ani( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_dds( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_png( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_apng( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_jpg( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_pcx( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_tga( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_user( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ushort flags );
void bm_lock_ani( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_dds( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_png( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_apng( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_jpg( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_pcx( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_tga( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
void bm_lock_user( int handle, bitmap_slot *bs, bitmap *bmp, int bpp, ubyte flags );
const size_t BM_BLOCK_SIZE = 4096;
Loaded 100 of 1159 files, more files were not shown because too many files have changed in this diff. Show more