Skip to content
Snippets Groups Projects
Commit 88b0c14d authored by Adrien Stucky's avatar Adrien Stucky
Browse files

Merge branch 'wasm-ci' into 'master'

Wasm ci

See merge request vtk/vtk-examples!321
parents ced16fb1 a8095f48
No related branches found
No related tags found
1 merge request!321Wasm ci
Pipeline #384250 passed
Showing
with 969 additions and 0 deletions
stages:
- prep
- build
- deploy
default:
image: ubuntu:22.04
tags:
- linux-x86_64
- build
- vtk-examples
artifacts:
expire_in: 1 day
build-vtk:
image: $CI_REGISTRY/vtk/vtk-examples:20240119
stage: prep
cache:
key: vtk-cache
paths:
- vtk
policy: pull-push
script:
- bash .gitlab/ci/scripts/build_vtk.sh
artifacts:
paths:
- vtk
package-data:
image: $CI_REGISTRY/vtk/vtk-examples:20240119
stage: build
script:
- bash .gitlab/ci/scripts/package_data.sh
artifacts:
paths:
- packaged_data/
build-examples:
image: $CI_REGISTRY/vtk/vtk-examples:20240119
stage: build
script:
- bash .gitlab/ci/scripts/build_examples.sh
artifacts:
paths:
- build_examples/
build-gh-pages:
rules:
- if: '$CI_COMMIT_REF_NAME == "master"'
stage: build
before_script:
- bash .gitlab/ci/scripts/before_build_gh-pages.sh
script:
- eval $(ssh-agent -s)
- ssh-add $GH_KEY
- bash .gitlab/ci/scripts/build_gh-pages.sh
environment:
name: deploy-gh-pages
url: https://github.com/Kitware/vtk-examples
deploy-examples:
rules:
- if: '$CI_COMMIT_REF_NAME == "master"'
needs:
- build-examples
stage: deploy
dependencies:
- build-examples
before_script:
- bash .gitlab/ci/scripts/before_deploy_examples.sh
script:
- eval $(ssh-agent -s)
- ssh-add $RSYNC_KEY
- bash .gitlab/ci/scripts/deploy_examples.sh
environment:
name: deploy-examples
url: https://web.kitware.com
deploy-data:
rules:
- if: '$CI_COMMIT_REF_NAME == "master"'
needs:
- package-data
stage: deploy
dependencies:
- package-data
before_script:
- bash .gitlab/ci/scripts/before_deploy_data.sh
script:
- eval $(ssh-agent -s)
- ssh-add $RSYNC_KEY
- bash .gitlab/ci/scripts/deploy_data.sh
environment:
name: deploy-examples
url: https://web.kitware.com
import argparse
import json
import shutil
import subprocess
import os
def GetParameters():
parser = argparse.ArgumentParser(description='', epilog='')
parser.add_argument('source_path')
parser.add_argument('dest_path')
parser.add_argument('vtk_source_path')
args = parser.parse_args()
return args.source_path, args.dest_path, args.vtk_source_path
def GenerateExample(example_name, source_path, dest_path, vtk_source_path):
shutil.copyfile('.gitlab/templates/index.html.template', os.path.join(dest_path, 'index.html'))
with open(os.path.join(dest_path, 'index.html'), 'r') as index:
data = index.read()
data = data.replace('XXX', example_name)
with open(os.path.join(dest_path, 'index.html'), 'w') as index:
index.write(data)
shutil.copyfile('.gitlab/templates/CMakeLists.txt.template', os.path.join(dest_path, 'CMakeLists.txt'))
with open(os.path.join(dest_path, 'CMakeLists.txt'), 'r') as cmake:
data = cmake.read()
data = data.replace('XXX', example_name)
try:
process = subprocess.run('python3 .gitlab/WhatModulesVTK.py ' + vtk_source_path + ' ' + source_path, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = process.stdout.decode('utf-8')
except subprocess.CalledProcessError as err:
print('ERROR:', err)
if err.returncode != 0:
print('returncode:', err.returncode)
print('Have {} bytes in stdout:\n{}'.format(
len(err.stdout),
err.stdout.decode('utf-8'))
)
print('Have {} bytes in stderr:\n{}'.format(
len(err.stderr),
err.stderr.decode('utf-8'))
)
result = f"# The following error occurred running {err.cmd}\n"
for line in err.stderr.decode('utf-8').split('\n'):
result += f"# {line}\n"
data = data.replace('ZZZ', result)
with open(os.path.join(dest_path, 'CMakeLists.txt'), 'w') as cmake:
cmake.write(data)
def GenerateExampleArgs(example_name, source_path, dest_path, vtk_source_path, args_data):
shutil.copyfile('.gitlab/templates/index_arguments.html.template', os.path.join(dest_path, 'index.html'))
with open(os.path.join(dest_path, 'index.html'), 'r') as index:
data = index.read()
data = data.replace('XXX', example_name)
module_arguments = []
for arg in args_data.get('args'):
module_arguments.append(arg)
data = data.replace('YYY', '\', \''.join(module_arguments))
script_lines = []
for file in args_data.get('files'):
script_lines.append('<script type="text/javascript" src="https://vtk.org/files/examples/data/' + file + '.js"></script>')
data = data.replace('ZZZ', '\n'.join(script_lines))
with open(os.path.join(dest_path, 'index.html'), 'w') as index:
index.write(data)
shutil.copyfile('.gitlab/templates/CMakeLists_arguments.txt.template', os.path.join(dest_path, 'CMakeLists.txt'))
with open(os.path.join(dest_path, 'CMakeLists.txt'), 'r') as cmake:
data = cmake.read()
data = data.replace('XXX', example_name)
try:
process = subprocess.run('python3 .gitlab/WhatModulesVTK.py ' + vtk_source_path + ' ' + source_path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = process.stdout.decode('utf-8')
except subprocess.CalledProcessError as err:
print('ERROR:', err)
if err.returncode != 0:
print('returncode:', err.returncode)
print('Have {} bytes in stdout:\n{}'.format(
len(err.stdout),
err.stdout.decode('utf-8'))
)
print('Have {} bytes in stderr:\n{}'.format(
len(err.stderr),
err.stderr.decode('utf-8'))
)
result = f"# The following error occurred running {err.cmd}\n"
for line in err.stderr.decode('utf-8').split('\n'):
result += f"# {line}\n"
data = data.replace('ZZZ', result)
with open(os.path.join(dest_path, 'CMakeLists.txt'), 'w') as cmake:
cmake.write(data)
def main():
source_path, dest_path, vtk_source_path = GetParameters()
example_name = os.path.splitext(os.path.basename(source_path))[0]
with open('src/Admin/WASM/ArgsNeeded.json') as f:
data = json.load(f)
if data.get(example_name, None):
print('arguments found')
GenerateExampleArgs(example_name, source_path, dest_path, vtk_source_path, data.get(example_name))
else:
print('no arguments found')
GenerateExample(example_name, source_path, dest_path, vtk_source_path)
if __name__ == '__main__':
main()
import shutil
import glob
shutil.copyfile('.gitlab/templates/CMakeLists_global.txt.template', 'pregen_examples/CMakeLists.txt')
with open('pregen_examples/CMakeLists.txt', 'r') as cmake:
data = cmake.read()
subdirectories = []
for path in glob.glob('pregen_examples/**/CMakeLists.txt', recursive=True):
if path != 'pregen_examples/CMakeLists.txt':
subdirectories.append('add_subdirectory(' + path.removeprefix('pregen_examples/').removesuffix('CMakeLists.txt') + ')')
data = data.replace('XXX', '\n'.join(subdirectories))
with open('pregen_examples/CMakeLists.txt', 'w') as cmake:
cmake.write(data)
#!/usr/bin/env python
import re
import sys
from collections import defaultdict
from pathlib import Path
def remove_prefix(text, prefix):
if sys.version_info > (3, 9):
return text.removeprefix(prefix)
else:
if text.startswith(prefix): # only modify the text if it starts with the prefix
text = text.replace(prefix, "", 1) # remove one instance of prefix
return text
def get_program_parameters():
import argparse
description = 'Generate a find_package(VTK COMPONENTS ...) that lists all modules referenced by a set of files.'
epilogue = '''
This uses the VTK source folder to determine the modules and headers.
Then the user files/folders are looked at to find the headers being used.
Finally a find_package() is output with the modules you need for
inclusion in your CMakeLists.txt file.
Note:
1) If include file(s) are not found when building your application.
You may need to search the VTK source to find where the file is.
Then look at contents of vtk.module in that folder and add the
module name to the find_package statement.
2) If linking fails, it usually means that the needed module has not been
built, so you may need to add it to your VTK build and rebuild VTK.
3) More modules than strictly necessary may be included.
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('vtk_path', help='The path to the VTK source tree.')
parser.add_argument('application', nargs='+', help='Paths to the application files or folders.')
args = parser.parse_args()
return args.vtk_path, args.application
def check_paths(vtk_src_dir, application_srcs):
"""
Check that the paths are valid.
:param vtk_src_dir: The path to the VTK source.
:param application_srcs: The user source files to be scanned for modules.
:return: True if paths, files exist.
"""
ok = True
if not Path(vtk_src_dir).is_dir():
print('The path to your VTK Source folder does not exist.')
print(Path(vtk_src_dir))
ok = False
bad_paths = list()
for f in application_srcs:
p = Path(f)
if not (p.is_dir() or p.is_file()):
bad_paths.append(p)
if bad_paths:
print('These application paths or files do not exist.')
for p in bad_paths:
print(p)
ok = False
return ok
def find_vtk_modules(vtk_src_dir):
"""
Build a dict of the VTK Module name, library name(if it exists) and any header files.
:param vtk_src_dir: The path to the VTK source folder
:return: Module name, library name and headers.
"""
vtk_modules = defaultdict(dict)
modules = [f for f in Path(vtk_src_dir).rglob('vtk.module')]
# Includes in the module path
file_patterns = ['vtk*.h', 'vtk*.h.in', 'QVTK*.h', '*QtQuick.h']
for module in modules:
content = module.read_text()
args = content.split('\n')
# Assuming NAME is always there.
if 'NAME' in args:
name = args[args.index('NAME') + 1].strip()
if 'LIBRARY_NAME' in args:
library_name = args[args.index('LIBRARY_NAME') + 1].strip()
else:
library_name = None
headers = list()
for pattern in file_patterns:
if pattern == 'vtk*.h.in':
# These files will be converted to header files in the build folder of VTK.
headers.extend([f.with_suffix('').name for f in module.parent.glob(pattern)])
else:
headers.extend([f.name for f in module.parent.glob(pattern)])
vtk_modules[name]['library_name'] = library_name
vtk_modules[name]['headers'] = headers
return vtk_modules
def build_headers_modules(modules):
"""
Make a dictionary whose key is the header filename and value is the module.
:param modules: The modules.
:return: Headers and their corresponding module.
"""
# The headers should be unique to a module, however we will not assume this.
headers_modules = defaultdict(set)
for k, v in modules.items():
if 'headers' in v:
for k1 in v['headers']:
headers_modules[k1].add(k)
return headers_modules
def find_application_includes(path):
"""
Build a set that contains the vtk includes found in the file.
:param path: The path to the application file.
:return: The includes that were found.
"""
includes = set()
include_hdr1 = re.compile(r'((?:vtk|QVTK).*\.h)')
include_hdr2 = re.compile(r'(\w+QtQuick\.h)')
content = path.read_text()
incs = include_hdr1.findall(content)
includes.update(incs)
incs = include_hdr2.findall(content)
includes.update(incs)
return includes
def generate_find_package(vtk_src_dir, application_srcs):
"""
Generate the find_package statement.
:param vtk_src_dir: The VTK source folder.
:param application_srcs: A list of application folders and or files.
:return: The find_package statement.
"""
vtk_modules = find_vtk_modules(vtk_src_dir)
# Test to see if VTK source is provided
if len(vtk_modules) == 0:
print(vtk_src_dir, 'is not a VTK source directory. It does not contain any vtk.module files.')
return None
vtk_headers_modules = build_headers_modules(vtk_modules)
valid_extensions = ['.h', '.hxx', '.txx', '.cpp', '.cxx', '.cc']
# Build a set of includes for all command line files
all_includes = set()
for app_src in application_srcs:
p = Path(app_src)
if p.is_file():
if p.suffix in valid_extensions:
all_includes.update(find_application_includes(p))
elif p.is_dir():
paths = list()
for ext in valid_extensions:
paths.extend([f for f in p.rglob('*' + ext) if f.is_file()])
for path in paths:
all_includes.update(find_application_includes(path))
if len(all_includes) == 0:
print('No VTK includes found in the application files.')
return None
# Build a set that contains all modules referenced in the user files.
all_modules = set()
for inc in all_includes:
if inc in vtk_headers_modules:
for m in vtk_headers_modules[inc]:
all_modules.add(m)
if 'VTK::RenderingCore' in all_modules:
all_modules.add('VTK::RenderingOpenGL2')
all_modules.add('VTK::InteractionStyle')
all_modules.add('VTK::RenderingFreeType')
# all_modules.add('VTK::RenderingGL2PSOpenGL2')
all_modules.add('VTK::RenderingContextOpenGL2')
if 'VTK::DomainsChemistry' in all_modules:
all_modules.add('VTK::DomainsChemistryOpenGL2')
if 'VTK::RenderingVolume' in all_modules:
all_modules.add('VTK::RenderingVolumeOpenGL2')
if 'VTK::RenderingContext2D' in all_modules:
all_modules.add('VTK::RenderingContextOpenGL2')
if 'VTK::IOExport' in all_modules:
all_modules.add('VTK::IOExportOpenGL2')
all_modules.add('VTK::IOExportPDF')
all_modules.add('VTK::RenderingContextOpenGL2')
res = ['find_package(VTK', ' COMPONENTS']
for m in sorted(all_modules):
m = remove_prefix(m, 'VTK::')
res.append(' ' * 2 + m)
res.append('REQUIRED)')
return res
def main():
vtk_src_dir, application_srcs = get_program_parameters()
if not check_paths(vtk_src_dir, application_srcs):
return
res = generate_find_package(vtk_src_dir, application_srcs)
if res:
print('\n'.join(res))
if __name__ == '__main__':
main()
FROM ubuntu:latest
SHELL ["/bin/bash", "-c"]
COPY install_deps.sh /
RUN bash install_deps.sh
COPY install_emsdk.sh /
RUN bash install_emsdk.sh
ENV PATH /emsdk:/emsdk/upstream/emscripten:/emsdk/node/16.20.0_64bit/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ENV EMSDK /emsdk
ENV EMSDK_NODE /emsdk/node/16.20.0_64bit/bin/node
CMD /bin/bash
#!/bin/bash
apt update -y
apt upgrade -y
apt install -y git python3 cmake git xz-utils ninja-build clang gcc unzip
apt clean -y
#!/bin/bash
git clone --depth 1 --branch 3.1.50 https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install 3.1.50
./emsdk activate 3.1.50
#!/bin/bash
apt update -y
apt install -y python3 python3-venv git openssh-client rsync
python3 -m venv venv/vtk-examples-web
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
chmod 644 ~/.ssh/known_hosts
chmod 400 $GH_KEY
git config --global user.email kwrobot+vtk-examples@kitware.com
git config --global user.name "Kitware Robot"
#!/bin/bash
apt update -y
apt install -y rsync openssh-client
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
chmod 644 ~/.ssh/known_hosts
chmod 400 $RSYNC_KEY
#!/bin/bash
apt update -y
apt install -y rsync openssh-client
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
chmod 644 ~/.ssh/known_hosts
chmod 400 $RSYNC_KEY
#!/bin/bash
exclude_dirs=(Deprecated Untested Databases Developers Snippets Qt)
shopt -s extglob
mkdir build_examples
mkdir pregen_examples
for topic in src/Cxx/*/; do
topic_name=$(basename ${topic})
if [[ ! $(echo ${exclude_dirs[@]} | grep -Fw ${topic_name}) ]]; then
for f in ${topic}/*.cxx; do
name=$(basename ${f} .cxx)
if ! grep -Fxq "$name" src/Admin/WASM/exclude_wasm.txt; then
echo ${name}
target_path=pregen_examples/${topic_name}/${name}
mkdir -p ${target_path}
cp ${f} ${target_path}
for addon_file in ${topic}/${name}.!(md); do
cp ${addon_file} ${target_path}
done
python3 .gitlab/GenerateHtmlCMake.py ${f} ${target_path} vtk
fi
done
fi
done
python3 .gitlab/GenerateSuperCMake.py
emcmake cmake -GNinja \
-DEMSCRIPTEN:Bool=true \
-DVTK_DIR=$CI_PROJECT_DIR/vtk/build \
-DDEBUGINFO=NONE \
-S pregen_examples -B build_examples
cmake --build build_examples
#!/bin/sh
source venv/vtk-examples-web/bin/activate
python -m pip install --upgrade pip
pip install wheel
pip install mkdocs-material htmlmin
git clone git@github.com:Kitware/vtk-examples.git /pages
pushd /pages
git checkout gh-pages
popd
OLDHOME=${HOME}
HOME=${PWD}
src/SyncSiteWithRepo.sh https://gitlab.kitware.com/vtk/vtk-examples https://examples.vtk.org/site/ https://github.com/Kitware/vtk-examples /pages vtk
HOME=${OLDHOME}
pushd /pages
git add .
git commit -m "nightly update"
git push
#!/bin/bash
if [ ! -d vtk ]; then
git clone https://gitlab.kitware.com/vtk/vtk.git
cd vtk
mkdir build
emcmake cmake \
-GNinja -DBUILD_SHARED_LIBS:BOOL=OFF \
-DCMAKE_BUILD_TYPE:STRING=Release \
-DVTK_ENABLE_LOGGING:BOOL=OFF \
-DVTK_ENABLE_WRAPPING:BOOL=OFF \
-DVTK_MODULE_ENABLE_VTK_cli11:STRING=YES \
-DVTK_MODULE_ENABLE_VTK_RenderingLICOpenGL2:STRING=DONT_WANT \
-DVTK_BUILD_TESTING=ON \
-S . -B build
else
cd vtk
git pull
fi
cmake --build build
#!/bin/bash
for file in packaged_data/*; do
gzip ${file}
mv ${file}.gz ${file}
done
rsync -av packaged_data/ kitware@web.kitware.com:/data/
#!/bin/bash
shopt -s extglob
for topic in build_examples/!(CMakeFiles)/; do
for example in ${topic}/*/; do
mkdir ${example}/upload
example_name=$(basename ${example})
gzip ${example}/${example_name}.wasm
mv ${example}/${example_name}.wasm.gz ${example}/upload/${example_name}.wasm
gzip ${example}/${example_name}.js
mv ${example}/${example_name}.js.gz ${example}/upload/${example_name}.js
gzip ${example}/index.html
mv ${example}/index.html.gz ${example}/upload/index.html
rsync -r ${example}/upload/ kitware@web.kitware.com:/${example_name}/
done
done
#!/bin/bash
for f in $(find src/SupplementaryData/Cxx -type f); do
if [[ "$f" == *.zip ]]; then
mkdir src/Testing/Data/$(basename $f .zip)
unzip $f -d src/Testing/Data/$(basename $f .zip)
else
cp $f src/Testing/Data
fi
done
mkdir packages_fs
python3 .gitlab/make_packages.py
mkdir packaged_data
for f in packages_fs/*; do
filename=$(basename $f)
/emsdk/upstream/emscripten/tools/file_packager packaged_data/${filename}.data --preload $f@/ --js-output=packaged_data/${filename}.js
done
import json
import shutil
import glob
import os
import errno
with open('src/Admin/WASM/packaged_files.json') as f:
data = json.load(f)
for package_attr, package_val in data.items():
os.makedirs('packages_fs/' + package_attr)
for filename_attr, filename_val in package_val.items():
if filename_val['type'] == 'dir':
os.makedirs('packages_fs/' + package_attr + '/' + filename_attr)
for target in filename_val['path']:
for globtarget in glob.glob('src/Testing/Data/' + target):
try:
shutil.copytree(globtarget, 'packages_fs/' + package_attr + '/' + filename_attr + '/' + os.path.basename(globtarget))
except OSError as exc: # copy file or directory
if exc.errno in (errno.ENOTDIR, errno.EINVAL):
shutil.copy(globtarget, 'packages_fs/' + package_attr + '/' + filename_attr)
elif exc.errno == errno.EEXIST:
pass
else: raise
else:
shutil.copy('src/Testing/Data/' + filename_val['path'][0], 'packages_fs/' + package_attr + '/' + filename_attr)
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(XXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# # -----------------------------------------------------------------------------
# # EMSCRIPTEN only
# # -----------------------------------------------------------------------------
if (NOT EMSCRIPTEN)
message("Skipping example: This needs to run inside an Emscripten build environment")
return ()
endif ()
# -----------------------------------------------------------------------------
# Handle VTK dependency
# -----------------------------------------------------------------------------
ZZZ
if (NOT VTK_FOUND)
message("Skipping example: ${VTK_NOT_FOUND_MESSAGE}")
return ()
endif ()
# -----------------------------------------------------------------------------
# Compile example code
# -----------------------------------------------------------------------------
add_executable(XXX XXX.cxx)
target_link_libraries(XXX
PRIVATE
${VTK_LIBRARIES}
)
# -----------------------------------------------------------------------------
# WebAssembly build options
# -----------------------------------------------------------------------------
set(emscripten_link_options)
set(emscripten_compile_options)
list(APPEND emscripten_link_options
"SHELL:-s WASM=1"
"SHELL:-s ALLOW_MEMORY_GROWTH=1"
"SHELL:-s STACK_SIZE=2mb"
)
set(emscripten_debug_options)
set(DEBUGINFO "PROFILE" CACHE STRING "Type of debug info")
set_property(CACHE DEBUGINFO PROPERTY
STRINGS
NONE # -g0
READABLE_JS # -g1
PROFILE # -g2
DEBUG_NATIVE # -g3
)
if(DEBUGINFO STREQUAL "NONE")
list(APPEND emscripten_debug_options
"-g0"
)
elseif(DEBUGINFO STREQUAL "READABLE_JS")
list(APPEND emscripten_debug_options
"-g1"
)
list(APPEND emscripten_link_options
"SHELL:-s DEMANGLE_SUPPORT=1"
)
elseif(DEBUGINFO STREQUAL "PROFILE")
list(APPEND emscripten_debug_options
"-g2"
)
list(APPEND emscripten_link_options
"SHELL:-s DEMANGLE_SUPPORT=1"
)
elseif(DEBUGINFO STREQUAL "DEBUG_NATIVE")
list(APPEND emscripten_debug_options
"-g3"
)
list(APPEND emscripten_link_options
"SHELL:-s ASSERTIONS=1"
"SHELL:-s DEMANGLE_SUPPORT=1"
)
endif()
# -----------------------------------------------------------------------------
# Build options
# -----------------------------------------------------------------------------
set(emscripten_optimizations)
set(OPTIMIZE "SMALLEST_WITH_CLOSURE" CACHE STRING "Emscripten optimization")
set_property(CACHE OPTIMIZE PROPERTY
STRINGS
NO_OPTIMIZATION # -O0
LITTLE # -O1
MORE # -O2
BEST # -O3
SMALL # -Os
SMALLEST # -Oz
SMALLEST_WITH_CLOSURE # -Oz --closure 1
)
if(OPTIMIZE STREQUAL "NO_OPTIMIZATION")
list(APPEND emscripten_optimizations
"-O0"
)
elseif(OPTIMIZE STREQUAL "LITTLE")
list(APPEND emscripten_optimizations
"-O1"
)
elseif(OPTIMIZE STREQUAL "MORE")
list(APPEND emscripten_optimizations
"-O2"
)
elseif(OPTIMIZE STREQUAL "BEST")
list(APPEND emscripten_optimizations
"-O3"
)
elseif(OPTIMIZE STREQUAL "SMALL")
list(APPEND emscripten_optimizations
"-Os"
)
elseif(OPTIMIZE STREQUAL "SMALLEST")
list(APPEND emscripten_optimizations
"-Oz"
)
elseif(OPTIMIZE STREQUAL "SMALLEST_WITH_CLOSURE")
list(APPEND emscripten_optimizations
"-Oz"
)
list(APPEND emscripten_link_options
"--closure 1"
)
endif()
target_compile_options(XXX
PUBLIC
${emscripten_compile_options}
${emscripten_optimizations}
${emscripten_debug_options}
)
target_link_options(XXX
PUBLIC
${emscripten_link_options}
${emscripten_optimizations}
${emscripten_debug_options}
)
# -----------------------------------------------------------------------------
# VTK modules initialization
# -----------------------------------------------------------------------------
vtk_module_autoinit(
TARGETS XXX
MODULES ${VTK_LIBRARIES}
)
# -----------------------------------------------------------------------------
# Copy HTML to build directory
# -----------------------------------------------------------------------------
add_custom_command(
TARGET XXX
POST_BUILD
COMMAND
${CMAKE_COMMAND} -E copy_if_different
"${CMAKE_CURRENT_SOURCE_DIR}/index.html"
$<TARGET_FILE_DIR:XXX>
)
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(XXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# # -----------------------------------------------------------------------------
# # EMSCRIPTEN only
# # -----------------------------------------------------------------------------
if (NOT EMSCRIPTEN)
message("Skipping example: This needs to run inside an Emscripten build environment")
return ()
endif ()
# -----------------------------------------------------------------------------
# Handle VTK dependency
# -----------------------------------------------------------------------------
ZZZ
if (NOT VTK_FOUND)
message("Skipping example: ${VTK_NOT_FOUND_MESSAGE}")
return ()
endif ()
# -----------------------------------------------------------------------------
# Compile example code
# -----------------------------------------------------------------------------
add_executable(XXX XXX.cxx)
target_link_libraries(XXX
PRIVATE
${VTK_LIBRARIES}
)
# -----------------------------------------------------------------------------
# WebAssembly build options
# -----------------------------------------------------------------------------
set(emscripten_link_options)
set(emscripten_compile_options)
list(APPEND emscripten_link_options
"SHELL:-s WASM=1"
"SHELL:-s ALLOW_MEMORY_GROWTH=1"
"SHELL:-s STACK_SIZE=2mb"
"SHELL:-s FORCE_FILESYSTEM"
)
list(APPEND emscripten_compile_options
"SHELL:-std=c++17"
)
set(emscripten_debug_options)
set(DEBUGINFO "PROFILE" CACHE STRING "Type of debug info")
set_property(CACHE DEBUGINFO PROPERTY
STRINGS
NONE # -g0
READABLE_JS # -g1
PROFILE # -g2
DEBUG_NATIVE # -g3
)
if(DEBUGINFO STREQUAL "NONE")
list(APPEND emscripten_debug_options
"-g0"
)
elseif(DEBUGINFO STREQUAL "READABLE_JS")
list(APPEND emscripten_debug_options
"-g1"
)
list(APPEND emscripten_link_options
"SHELL:-s DEMANGLE_SUPPORT=1"
)
elseif(DEBUGINFO STREQUAL "PROFILE")
list(APPEND emscripten_debug_options
"-g2"
)
list(APPEND emscripten_link_options
"SHELL:-s DEMANGLE_SUPPORT=1"
)
elseif(DEBUGINFO STREQUAL "DEBUG_NATIVE")
list(APPEND emscripten_debug_options
"-g3"
)
list(APPEND emscripten_link_options
"SHELL:-s ASSERTIONS=1"
"SHELL:-s DEMANGLE_SUPPORT=1"
)
endif()
# -----------------------------------------------------------------------------
# Build options
# -----------------------------------------------------------------------------
set(emscripten_optimizations)
set(OPTIMIZE "SMALLEST_WITH_CLOSURE" CACHE STRING "Emscripten optimization")
set_property(CACHE OPTIMIZE PROPERTY
STRINGS
NO_OPTIMIZATION # -O0
LITTLE # -O1
MORE # -O2
BEST # -O3
SMALL # -Os
SMALLEST # -Oz
SMALLEST_WITH_CLOSURE # -Oz --closure 1
)
if(OPTIMIZE STREQUAL "NO_OPTIMIZATION")
list(APPEND emscripten_optimizations
"-O0"
)
elseif(OPTIMIZE STREQUAL "LITTLE")
list(APPEND emscripten_optimizations
"-O1"
)
elseif(OPTIMIZE STREQUAL "MORE")
list(APPEND emscripten_optimizations
"-O2"
)
elseif(OPTIMIZE STREQUAL "BEST")
list(APPEND emscripten_optimizations
"-O3"
)
elseif(OPTIMIZE STREQUAL "SMALL")
list(APPEND emscripten_optimizations
"-Os"
)
elseif(OPTIMIZE STREQUAL "SMALLEST")
list(APPEND emscripten_optimizations
"-Oz"
)
elseif(OPTIMIZE STREQUAL "SMALLEST_WITH_CLOSURE")
list(APPEND emscripten_optimizations
"-Oz"
)
list(APPEND emscripten_link_options
"--closure 1"
)
endif()
target_compile_options(XXX
PUBLIC
${emscripten_compile_options}
${emscripten_optimizations}
${emscripten_debug_options}
)
target_link_options(XXX
PUBLIC
${emscripten_link_options}
${emscripten_optimizations}
${emscripten_debug_options}
)
# -----------------------------------------------------------------------------
# VTK modules initialization
# -----------------------------------------------------------------------------
vtk_module_autoinit(
TARGETS XXX
MODULES ${VTK_LIBRARIES}
)
# -----------------------------------------------------------------------------
# Copy HTML to build directory
# -----------------------------------------------------------------------------
add_custom_command(
TARGET XXX
POST_BUILD
COMMAND
${CMAKE_COMMAND} -E copy_if_different
"${CMAKE_CURRENT_SOURCE_DIR}/index.html"
$<TARGET_FILE_DIR:XXX>
)
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(vtk-examples)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
XXX
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment